CodeIgniter Documentation 3.0-dev

EllisLab, Inc.

2014 02 02

Contents

i ii CodeIgniter Documentation, 3.0-dev

• License Agreement • Change Log

• • • • • • • • Driver • • CodeIgniter

Contents 1 CodeIgniter Documentation, 3.0-dev

2 Contents CHAPTER 1

• Welcome to CodeIgniter

3 CodeIgniter Documentation, 3.0-dev

4 Chapter 1. CHAPTER 2

• Server Requirements • Credits

5 CodeIgniter Documentation, 3.0-dev

6 Chapter 2. CHAPTER 3

• Downloading CodeIgniter • Installation Instructions • Upgrading From a Previous Version • Troubleshooting

7 CodeIgniter Documentation, 3.0-dev

8 Chapter 3. CHAPTER 4

• Getting Started With CodeIgniter • CodeIgniter at a Glance • CodeIgniter Features • Application Flow Chart • Model-View-Controller • Design and Architectural Goals

9 CodeIgniter Documentation, 3.0-dev

10 Chapter 4. CHAPTER 5

• Tutorial • Static pages • News section • Create news items • Conclusion

11 CodeIgniter Documentation, 3.0-dev

12 Chapter 5. CHAPTER 6

6.1 General Topics

6.1.1 CodeIgniter URLs

By default, URLs in CodeIgniter are designed to be search-engine and human friendly. Rather than using the standard “query string” approach to URLs that is synonymous with dynamic systems, CodeIgniter uses a segment-based approach: example.com/news/article/my_article

: Query string URLs can be optionally enabled, as described below.

URI Segments

The segments in the URL, in following with the Model-View-Controller approach, usually represent: example.com/class/function/ID

1. The first segment represents the controller class that should be invoked. 2. The second segment represents the class function, or method, that should be called. 3. The third, and any additional segments, represent the ID and any variables that will be passed to the controller. The URI Library and the URL Helper contain functions that make it easy to work with your URI data. In addition, your URLs can be remapped using the URI Routing feature for more flexibility.

Removing the index. file

By default, the index.php file will be included in your URLs: example.com/index.php/news/article/my_article

If your Apache server has mod_rewrite enabled, you can easily remove this file by using a .htaccess file with some simple rules. Here is an example of such a file, using the “negative” method in which everything is redirected except the specified items:

13 CodeIgniter Documentation, 3.0-dev

RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !- RewriteRule ^(.*)$ index.php/$1 [L]

In the above example, any HTTP request other than those for existing directories and existing files is treated as a request for your index.php file.

: These specific rules might not work for all server configurations.

: Make sure to also exclude from the above rule any assets that you might need to be accessible from the outside world.

Adding a URL Suffix

In your config/config.php file you can specify a suffix that will be added to all URLs generated by CodeIgniter. For example, if a URL is this: example.com/index.php/products/view/shoes

You can optionally add a suffix, like .html, making the page appear to be of a certain type: example.com/index.php/products/view/shoes.html

Enabling Query Strings

In some cases you might prefer to use query strings URLs: index.php?c=products&m=view&id=345

CodeIgniter optionally supports this capability, which can be enabled in your application/config.php file. If you open your config file you’ll see these items: $config[’enable_query_strings’] = FALSE; $config[’controller_trigger’] = ’c’; $config[’function_trigger’] = ’m’;

If you change “enable_query_strings” to TRUE this feature will become active. Your controllers and functions will then be accessible using the “trigger” words you’ve set to invoke your controllers and methods: index.php?c=controller&m=method

: If you are using query strings you will have to build your own URLs, rather than utilizing the URL helpers (and other helpers that generate URLs, like some of the form helpers) as these are designed to work with segment based URLs.

6.1.2 Controllers

Controllers are the heart of your application, as they determine how HTTP requests should be handled.

14 Chapter 6. CodeIgniter Documentation, 3.0-dev

Page Contents • Controllers – What is a Controller? – Let’s try it: Hello World! – Methods – Passing URI Segments to your methods – Defining a Default Controller – Remapping Method Calls – Processing Output – Private methods – Organizing Your Controllers into Sub-directories – Class Constructors – Reserved method names – That’s it!

What is a Controller?

A Controller is simply a class file that is named in a way that can be associated with a URI. Consider this URI: example.com/index.php/blog/

In the above example, CodeIgniter would attempt to find a controller named Blog.php and load it. When a controller’s name matches the first segment of a URI, it will be loaded.

Let’s try it: Hello World!

Let’s create a simple controller so you can see it in action. Using your text editor, create a file called Blog.php, and put the following code in it:

public function index() { echo ’Hello World!’; } }

Then save the file to your application/controllers/ directory.

: The file must be called ‘Blog.php’, with a capital ‘B’.

Now visit the your site using a URL similar to this: example.com/index.php/blog/

If you did it right, you should see: Hello World!

6.1. General Topics 15 CodeIgniter Documentation, 3.0-dev

: Class names must start with an uppercase letter.

This is valid:

}

This is not valid:

}

Also, always make sure your controller extends the parent controller class so that it can inherit all its methods.

Methods

In the above example the method name is index(). The “index” method is always loaded by default if the second segment of the URI is empty. Another way to show your “Hello World” message would be this: example.com/index.php/blog/index/

The second segment of the URI determines which method in the controller gets called. Let’s try it. Add a new method to your controller:

public function index() { echo ’Hello World!’; }

public function comments() { echo ’Look at this!’; } }

Now load the following URL to see the comment method: example.com/index.php/blog/comments/

You should see your new message.

Passing URI Segments to your methods

If your URI contains more then two segments they will be passed to your method as parameters. For example, let’s say you have a URI like this: example.com/index.php/products/shoes/sandals/123

16 Chapter 6. CodeIgniter Documentation, 3.0-dev

Your method will be passed URI segments 3 and 4 (“sandals” and “123”):

public function shoes($sandals, $id) { echo $sandals; echo $id; } }

: If you are using the URI Routing feature, the segments passed to your method will be the re-routed ones.

Defining a Default Controller

CodeIgniter can be told to load a default controller when a URI is not present, as will be the case when only your site root URL is requested. To specify a default controller, open your application/config/routes.php file and set this variable: $route[’default_controller’] = ’Blog’;

Where Blog is the name of the controller class you want used. If you now load your main index.php file without specifying any URI segments you’ll see your Hello World message by default.

Remapping Method Calls

As noted above, the second segment of the URI typically determines which method in the controller gets called. CodeIgniter permits you to override this behavior through the use of the _remap() method: public function _remap() { // Some code here... }

: If your controller contains a method named _remap(), it will always get called regardless of what your URI contains. It overrides the normal behavior in which the URI determines which method is called, allowing you to define your own method routing rules.

The overridden method call (typically the second segment of the URI) will be passed as a parameter to the _remap() method: public function _remap($method) { if ($method === ’some_method’) { $this->$method(); } else { $this->default_method(); } }

6.1. General Topics 17 CodeIgniter Documentation, 3.0-dev

Any extra segments after the method name are passed into _remap() as an optional second parameter. This array can be used in combination with PHP’s call_user_func_array() to emulate CodeIgniter’s default behavior. Example: public function _remap($method, $params = array()) { $method = ’process_’.$method; if (method_exists($this, $method)) { return call_user_func_array(array($this, $method), $params); } show_404(); }

Processing Output

CodeIgniter has an output class that takes care of sending your final rendered data to the web browser automatically. More information on this can be found in the Views and Output Class pages. In some cases, however, you might want to post-process the finalized data in some way and send it to the browser yourself. CodeIgniter permits you to add a method named _output() to your controller that will receive the finalized output data.

: If your controller contains a method named _output(), it will always be called by the output class instead of echoing the finalized data directly. The first parameter of the method will contain the finalized output.

Here is an example: public function _output($output) { echo $output; }

: Please note that your _output() method will receive the data in its finalized state. Benchmark and memory usage data will be rendered, cache files written (if you have caching enabled), and headers will be sent (if you use that feature) before it is handed off to the _output() method. To have your controller’s output cached properly, its _output() method can use: if ($this->output->cache_expiration > 0) { $this->output->_write_cache($output); }

If you are using this feature the page execution timer and memory usage stats might not be perfectly accurate since they will not take into account any further processing you do. For an alternate way to control output before any of the final processing is done, please see the available methods in the Output Library.

Private methods

In some cases you may want certain methods hidden from public access. In order to achieve this, simply declare the method as being private or protected and it will not be served via a URL request. For example, if you were to have a method like this: private function _utility() {

18 Chapter 6. CodeIgniter Documentation, 3.0-dev

// some code }

Trying to access it via the URL, like this, will not work: example.com/index.php/blog/_utility/

: Prefixing method names with an underscore will also prevent them from being called. This is a legacy feature that is left for backwards-compatibility.

Organizing Your Controllers into Sub-directories

If you are building a large application you might find it convenient to organize your controllers into sub-directories. CodeIgniter permits you to do this. Simply create folders within your application/controllers/ directory and place your controller classes within them.

: When using this feature the first segment of your URI must specify the folder. For example, let’s say you have a controller located here: application/controllers/products/Shoes.php

To call the above controller your URI will look something like this: example.com/index.php/products/shoes/show/123

Each of your sub-directories may contain a default controller which will be called if the URL contains only the sub- folder. Simply name your default controller as specified in your application/config/routes.php file. CodeIgniter also permits you to remap your URIs using its URI Routing feature.

Class Constructors

If you intend to use a constructor in any of your Controllers, you MUST place the following line of code in it: parent::__construct();

The reason this line is necessary is because your local constructor will be overriding the one in the parent controller class so we need to manually call it. Example:

public function __construct() { parent::__construct(); // Your own constructor code } }

Constructors are useful if you need to set some default values, or run a default process when your class is instantiated. Constructors can’t return a value, but they can do some default work.

6.1. General Topics 19 CodeIgniter Documentation, 3.0-dev

Reserved method names

Since your controller classes will extend the main application controller you must be careful not to name your methods identically to the ones used by that class, otherwise your local functions will override them. See Reserved Names for a full list.

: You should also never have a method named identically to its class name. If you do, and there is no __construct() method in the same class, then your e.g. Index::index() method will be executed as a class constructor! This is a PHP4 backwards-compatibility feature.

That’s it!

That, in a nutshell, is all there is to know about controllers.

6.1.3 Reserved Names

In order to help out, CodeIgniter uses a series of function, method, class and variable names in its operation. Because of this, some names cannot be used by a developer. Following is a list of reserved names that cannot be used.

Controller names

Since your controller classes will extend the main application controller you must be careful not to name your methods identically to the ones used by that class, otherwise your local methods will override them. The following is a list of reserved names. Do not name your controller any of these: • Controller • CI_Base • _ci_initialize • Default • index

Functions

• is_php() • is_really_writable() • load_class() • is_loaded() • get_config() • config_item() • show_error() • show_404() • log_message() • set_status_header() • get_mimes()

20 Chapter 6. CodeIgniter Documentation, 3.0-dev

• html_escape() • remove_invisible_characters() • is_https() • function_usable() • get_instance() • _exception_handler() • _stringify_attributes()

Variables

• $config • $db • $lang

Constants

• ENVIRONMENT • FCPATH • SELF • BASEPATH • APPPATH • VIEWPATH • CI_VERSION • FILE_READ_MODE • FILE_WRITE_MODE • DIR_READ_MODE • DIR_WRITE_MODE • FOPEN_READ • FOPEN_READ_WRITE • FOPEN_WRITE_CREATE_DESTRUCTIVE • FOPEN_READ_WRITE_CREATE_DESTRUCTIVE • FOPEN_WRITE_CREATE • FOPEN_READ_WRITE_CREATE • FOPEN_WRITE_CREATE_STRICT • FOPEN_READ_WRITE_CREATE_STRICT • EXIT_SUCCESS • EXIT_ERROR • EXIT_CONFIG

6.1. General Topics 21 CodeIgniter Documentation, 3.0-dev

• EXIT_UNKNOWN_FILE • EXIT_UNKNOWN_CLASS • EXIT_UNKNOWN_METHOD • EXIT_USER_INPUT • EXIT_DATABASE • EXIT__AUTO_MIN • EXIT__AUTO_MAX

6.1.4 Views

A view is simply a web page, or a page fragment, like a header, footer, sidebar, etc. In fact, views can flexibly be embedded within other views (within other views, etc., etc.) if you need this type of hierarchy. Views are never called directly, they must be loaded by a controller. Remember that in an MVC framework, the Controller acts as the traffic cop, so it is responsible for fetching a particular view. If you have not read the Controllers page you should do so before continuing. Using the example controller you created in the controller page, let’s add a view to it.

Creating a View

Using your text editor, create a file called blogview.php, and put this in it: My Blog

Welcome to my Blog!

Then save the file in your application/views/ directory.

Loading a View

To load a particular view file you will use the following method: $this->load->view(’name’);

Where name is the name of your view file.

: The .php file extension does not need to be specified unless you use something other than .php.

Now, open the controller file you made earlier called Blog.php, and replace the echo statement with the view loading method:

public function index() {

22 Chapter 6. CodeIgniter Documentation, 3.0-dev

$this->load->view(’blogview’); } }

If you visit your site using the URL you did earlier you should see your new view. The URL was similar to this: example.com/index.php/blog/

Loading multiple views

CodeIgniter will intelligently handle multiple calls to $this->load->view() from within a controller. If more than one call happens they will be appended together. For example, you may wish to have a header view, a menu view, a content view, and a footer view. That might look something like this:

public function index() { $data[’page_title’] = ’Your title’; $this->load->view(’header’); $this->load->view(’menu’); $this->load->view(’content’, $data); $this->load->view(’footer’); }

}

In the example above, we are using “dynamically added data”, which you will see below.

Storing Views within Sub-directories

Your view files can also be stored within sub-directories if you prefer that type of organization. When doing so you will need to include the directory name loading the view. Example: $this->load->view(’directory_name/file_name’);

Adding Dynamic Data to the View

Data is passed from the controller to the view by way of an array or an object in the second parameter of the view loading method. Here is an example using an array: $data = array( ’title’ => ’My Title’, ’heading’ => ’My Heading’, ’message’ => ’My Message’ );

$this->load->view(’blogview’, $data);

And here’s an example using an object: $data = new Someclass(); $this->load->view(’blogview’, $data);

6.1. General Topics 23 CodeIgniter Documentation, 3.0-dev

: If you use an object, the class variables will be turned into array elements.

Let’s try it with your controller file. Open it add this code:

public function index() { $data[’title’] = "My Real Title"; $data[’heading’] = "My Real Heading";

$this->load->view(’blogview’, $data); } }

Now open your view file and change the text to variables that correspond to the array keys in your data: <?php echo $title;?>

Then load the page at the URL you’ve been using and you should see the variables replaced.

Creating Loops

The data array you pass to your view files is not limited to simple variables. You can pass multi dimensional arrays, which can be looped to generate multiple rows. For example, if you pull data from your database it will typically be in the form of a multi-dimensional array. Here’s a simple example. Add this to your controller:

public function index() { $data[’todo_list’] = array(’Clean House’, ’Call Mom’, ’Run Errands’);

$data[’title’] = "My Real Title"; $data[’heading’] = "My Real Heading";

$this->load->view(’blogview’, $data); } }

Now open your view file and create a loop: <?php echo $title;?>

24 Chapter 6. CodeIgniter Documentation, 3.0-dev

My Todo List

: You’ll notice that in the example above we are using PHP’s alternative syntax. If you are not familiar with it you can read about it here.

Returning views as data

There is a third optional parameter lets you change the behavior of the method so that it returns data as a string rather than sending it to your browser. This can be useful if you want to process the data in some way. If you set the parameter to TRUE (boolean) it will return data. The default behavior is false, which sends it to your browser. Remember to assign it to a variable if you want the data returned: $string = $this->load->view(’myfile’, ’’, TRUE);

6.1.5 Models

Models are optionally available for those who want to use a more traditional MVC approach.

Page Contents • Models – What is a Model? – Anatomy of a Model – Loading a Model – Auto-loading Models – Connecting to your Database

What is a Model?

Models are PHP classes that are designed to work with information in your database. For example, let’s say you use CodeIgniter to manage a blog. You might have a model class that contains functions to insert, update, and retrieve your blog data. Here is an example of what such a model class might look like: class Blog_model extends CI_Model {

public $title; public $content; public $date;

6.1. General Topics 25 CodeIgniter Documentation, 3.0-dev

public function __construct() { // Call the CI_Model constructor parent::__construct(); }

public function get_last_ten_entries() { $query = $this->db->get(’entries’, 10); return $query->result(); }

public function insert_entry() { $this->title = $_POST[’title’]; // please read the below note $this->content = $_POST[’content’]; $this->date = time();

$this->db->insert(’entries’, $this); }

public function update_entry() { $this->title = $_POST[’title’]; $this->content = $_POST[’content’]; $this->date = time();

$this->db->update(’entries’, $this, array(’id’ => $_POST[’id’])); }

}

: The methods in the above example use the Query Builder database methods.

: For the sake of simplicity in this example we’re using $_POST directly. This is generally bad practice, and a more common approach would be to use the Input Library $this->input->post(’title’).

Anatomy of a Model

Model classes are stored in your application/models/ directory. They can be nested within sub-directories if you want this type of organization. The basic prototype for a model class is this: class Model_name extends CI_Model {

public function __construct() { parent::__construct(); }

}

Where Model_name is the name of your class. Class names must have the first letter capitalized with the rest of the name lowercase. Make sure your class extends the base Model class.

26 Chapter 6. CodeIgniter Documentation, 3.0-dev

The file name must match the class name. For example, if this is your class: class User_model extends CI_Model {

public function __construct() { parent::__construct(); }

}

Your file will be this: application/models/User_model.php

Loading a Model

Your models will typically be loaded and called from within your controller methods. To load a model you will use the following method: $this->load->model(’model_name’);

If your model is located in a sub-directory, include the relative path from your models directory. For example, if you have a model located at application/models/blog/Queries.php you’ll load it using: $this->load->model(’blog/queries’);

Once loaded, you will access your model methods using an object with the same name as your class: $this->load->model(’model_name’);

$this->model_name->method();

If you would like your model assigned to a different object name you can specify it via the second parameter of the loading method: $this->load->model(’model_name’, ’foobar’);

$this->foobar->method();

Here is an example of a controller, that loads a model, then serves a view: class Blog_controller extends CI_Controller {

public function blog() { $this->load->model(’blog’);

$data[’query’] = $this->Blog->get_last_ten_entries();

$this->load->view(’blog’, $data); } }

Auto-loading Models

If you find that you need a particular model globally throughout your application, you can tell CodeIgniter to auto- load it during system initialization. This is done by opening the application/config/autoload.php file and adding the

6.1. General Topics 27 CodeIgniter Documentation, 3.0-dev model to the autoload array.

Connecting to your Database

When a model is loaded it does NOT connect automatically to your database. The following options for connecting are available to you: • You can connect using the standard database methods described here, either from within your Controller class or your Model class. • You can tell the model loading method to auto-connect by passing TRUE (boolean) via the third parameter, and connectivity settings, as defined in your database config file will be used: $this->load->model(’model_name’, ’’, TRUE);

• You can manually pass database connectivity settings via the third parameter: $config[’hostname’] = ’localhost’; $config[’username’] = ’myusername’; $config[’password’] = ’mypassword’; $config[’database’] = ’mydatabase’; $config[’dbdriver’] = ’mysqli’; $config[’dbprefix’] = ’’; $config[’pconnect’] = FALSE; $config[’db_debug’] = TRUE;

$this->load->model(’model_name’, ’’, $config);

6.1.6 Helper Functions

Helpers, as the name suggests, help you with tasks. Each helper file is simply a collection of functions in a particular category. There are URL Helpers, that assist in creating links, there are Form Helpers that help you create form elements, Text Helpers perform various text formatting routines, Cookie Helpers set and read cookies, File Helpers help you deal with files, etc. Unlike most other systems in CodeIgniter, Helpers are not written in an Object Oriented format. They are simple, procedural functions. Each helper function performs one specific task, with no dependence on other functions. CodeIgniter does not load Helper Files by default, so the first step in using a Helper is to load it. Once loaded, it becomes globally available in your controller and views. Helpers are typically stored in your system/helpers, or application/helpers directory. CodeIgniter will look first in your application/helpers directory. If the directory does not exist or the specified helper is not located there CI will instead look in your global system/helpers/ directory.

Loading a Helper

Loading a helper file is quite simple using the following method: $this->load->helper(’name’);

Where name is the file name of the helper, without the .php file extension or the “helper” part. For example, to load the URL Helper file, which is named url_helper.php, you would do this: $this->load->helper(’url’);

28 Chapter 6. CodeIgniter Documentation, 3.0-dev

A helper can be loaded anywhere within your controller methods (or even within your View files, although that’s not a good practice), as long as you load it before you use it. You can load your helpers in your controller constructor so that they become available automatically in any function, or you can load a helper in a specific function that needs it.

: The Helper loading method above does not return a value, so don’t try to assign it to a variable. Just use it as shown.

Loading Multiple Helpers

If you need to load more than one helper you can specify them in an array, like this: $this->load->helper( array(’helper1’, ’helper2’, ’helper3’) );

Auto-loading Helpers

If you find that you need a particular helper globally throughout your application, you can tell CodeIgniter to auto- load it during system initialization. This is done by opening the application/config/autoload.php file and adding the helper to the autoload array.

Using a Helper

Once you’ve loaded the Helper File containing the function you intend to use, you’ll call it the way you would a standard PHP function. For example, to create a link using the anchor() function in one of your view files you would do this:

Where “Click Here” is the name of the link, and “blog/comments” is the URI to the controller/method you wish to link to.

“Extending” Helpers

To “extend” Helpers, create a file in your application/helpers/ folder with an identical name to the existing Helper, but prefixed with MY_ (this item is configurable. See below.). If all you need to do is add some functionality to an existing helper - perhaps add a function or two, or change how a particular helper function operates - then it’s overkill to replace the entire helper with your version. In this case it’s better to simply “extend” the Helper.

: The term “extend” is used loosely since Helper functions are procedural and discrete and cannot be extended in the traditional programmatic sense. Under the hood, this gives you the ability to add to or or to replace the functions a Helper provides.

For example, to extend the native Array Helper you’ll create a file named applica- tion/helpers/MY_array_helper.php, and add or override functions: // any_in_array() is not in the Array Helper, so it defines a new function function any_in_array($needle, $haystack) { $needle = is_array($needle) ? $needle : array($needle);

6.1. General Topics 29 CodeIgniter Documentation, 3.0-dev

foreach ($needle as $item) { if (in_array($item, $haystack)) { return TRUE; } }

return FALSE; }

// random_element() is included in Array Helper, so it overrides the native function function random_element($array) { shuffle($array); return array_pop($array); }

Setting Your Own Prefix

The filename prefix for “extending” Helpers is the same used to extend libraries and core classes. To set your own prefix, open your application/config/config.php file and look for this item: $config[’subclass_prefix’] = ’MY_’;

Please note that all native CodeIgniter libraries are prefixed with CI_ so DO NOT use that as your prefix.

Now What?

In the Table of Contents you’ll find a list of all the available Helper Files. Browse each one to see what they do.

6.1.7 Using CodeIgniter Libraries

All of the available libraries are located in your system/libraries/ directory. In most cases, to use one of these classes involves initializing it within a controller using the following initialization method: $this->load->library(’class_name’);

Where ‘class_name’ is the name of the class you want to invoke. For example, to load the Form Validation Library you would do this: $this->load->library(’form_validation’);

Once initialized you can use it as indicated in the user guide page corresponding to that class. Additionally, multiple libraries can be loaded at the same time by passing an array of libraries to the load method. Example: $this->load->library(array(’email’, ’table’));

Creating Your Own Libraries

Please read the section of the user guide that discusses how to create your own libraries.

30 Chapter 6. CodeIgniter Documentation, 3.0-dev

6.1.8 Creating Libraries

When we use the term “Libraries” we are normally referring to the classes that are located in the libraries directory and described in the Class Reference of this user guide. In this case, however, we will instead describe how you can create your own libraries within your application/libraries directory in order to maintain separation between your local resources and the global framework resources. As an added bonus, CodeIgniter permits your libraries to extend native classes if you simply need to add some func- tionality to an existing library. Or you can even replace native libraries just by placing identically named versions in your application/libraries directory. In summary: • You can create entirely new libraries. • You can extend native libraries. • You can replace native libraries. The page below explains these three concepts in detail.

: The Database classes can not be extended or replaced with your own classes. All other classes are able to be replaced/extended.

Storage

Your library classes should be placed within your application/libraries directory, as this is where CodeIgniter will look for them when they are initialized.

Naming Conventions

• File names must be capitalized. For example: Myclass.php • Class declarations must be capitalized. For example: class Myclass • Class names and file names must match.

The Class File

Classes should have this basic prototype:

public function some_method() { } }

/* End of file Someclass.php */

: We are using the name Someclass purely as an example.

6.1. General Topics 31 CodeIgniter Documentation, 3.0-dev

Using Your Class

From within any of your Controller methods you can initialize your class using the standard: $this->load->library(’someclass’);

Where someclass is the file name, without the ”.php” file extension. You can submit the file name capitalized or lower case. CodeIgniter doesn’t care. Once loaded you can access your class using the lower case version: $this->someclass->some_method(); // Object instances will always be lower case

Passing Parameters When Initializing Your Class

In the library loading method you can dynamically pass data as an array via the second parameter and it will be passed to your class constructor: $params = array(’type’ => ’large’, ’color’ => ’red’);

$this->load->library(’someclass’, $params);

If you use this feature you must set up your class constructor to expect data:

public function __construct($params) { // Do something with $params } }

You can also pass parameters stored in a config file. Simply create a config file named identically to the class file name and store it in your application/config/ directory. Note that if you dynamically pass parameters as described above, the config file option will not be available.

Utilizing CodeIgniter Resources within Your Library

To access CodeIgniter’s native resources within your library use the get_instance() method. This method returns the CodeIgniter super object. Normally from within your controller methods you will call any of the available CodeIgniter methods using the $this construct: $this->load->helper(’url’); $this->load->library(’session’); $this->config->item(’base_url’); // etc.

$this, however, only works directly within your controllers, your models, or your views. If you would like to use CodeIgniter’s classes from within your own custom classes you can do so as follows: First, assign the CodeIgniter object to a variable: $CI =& get_instance();

32 Chapter 6. CodeIgniter Documentation, 3.0-dev

Once you’ve assigned the object to a variable, you’ll use that variable instead of $this: $CI =& get_instance();

$CI->load->helper(’url’); $CI->load->library(’session’); $CI->config->item(’base_url’); // etc.

: You’ll notice that the above get_instance() function is being passed by reference: $CI =& get_instance();

This is very important. Assigning by reference allows you to use the original CodeIgniter object rather than creating a copy of it.

However, since a library is a class, it would be better if you take full advantage of the OOP principles. So, in order to be able to use the CodeIgniter super-object in all of the class methods, you’re encouraged to assign it to a property instead: class Example_library {

protected $CI;

// We’ll use a constructor, as you can’t directly call a function // from a property definition. public function __construct() { // Assign the CodeIgniter super-object $this->CI =& get_instance(); }

public function foo() { $this->CI->load->helper(’url’); redirect(); }

public function bar() { echo $this->CI->config_item(’base_url’); }

}

Replacing Native Libraries with Your Versions

Simply by naming your class files identically to a native library will cause CodeIgniter to use it instead of the native one. To use this feature you must name the file and the class declaration exactly the same as the native library. For example, to replace the native Email library you’ll create a file named application/libraries/Email.php, and declare your class with: class CI_Email {

}

Note that most native classes are prefixed with CI_.

6.1. General Topics 33 CodeIgniter Documentation, 3.0-dev

To load your library you’ll see the standard loading method: $this->load->library(’email’);

: At this time the Database classes can not be replaced with your own versions.

Extending Native Libraries

If all you need to do is add some functionality to an existing library - perhaps add a method or two - then it’s overkill to replace the entire library with your version. In this case it’s better to simply extend the class. Extending a class is nearly identical to replacing a class with a couple exceptions: • The class declaration must extend the parent class. • Your new class name and filename must be prefixed with MY_ (this item is configurable. See below.). For example, to extend the native Email class you’ll create a file named application/libraries/MY_Email.php, and declare your class with: class MY_Email extends CI_Email {

}

If you need to use a constructor in your class make sure you extend the parent constructor: class MY_Email extends CI_Email {

public function __construct($config = array()) { parent::__construct($config); }

}

: Not all of the libraries have the same (or any) parameters in their constructor. Take a look at the library that you’re extending first to see how it should be implemented.

Loading Your Sub-class

To load your sub-class you’ll use the standard syntax normally used. DO NOT include your prefix. For example, to load the example above, which extends the Email class, you will use: $this->load->library(’email’);

Once loaded you will use the class variable as you normally would for the class you are extending. In the case of the email class all calls will use: $this->email->some_method();

Setting Your Own Prefix

To set your own sub-class prefix, open your application/config/config.php file and look for this item:

34 Chapter 6. CodeIgniter Documentation, 3.0-dev

$config[’subclass_prefix’] = ’MY_’;

Please note that all native CodeIgniter libraries are prefixed with CI_ so DO NOT use that as your prefix.

6.1.9 Using CodeIgniter Drivers

Drivers are a special type of Library that has a parent class and any number of potential child classes. Child classes have access to the parent class, but not their siblings. Drivers provide an elegant syntax in your controllers for libraries that benefit from or require being broken down into discrete classes. Drivers are found in the system/libraries/ directory, in their own sub-directory which is identically named to the parent library class. Also inside that directory is a subdirectory named drivers, which contains all of the possible child class files. To use a driver you will initialize it within a controller using the following initialization method: $this->load->driver(’class_name’);

Where class name is the name of the driver class you want to invoke. For example, to load a driver named “Some_parent” you would do this: $this->load->driver(’some_parent’);

Methods of that class can then be invoked with: $this->some_parent->some_method();

The child classes, the drivers themselves, can then be called directly through the parent class, without initializing them: $this->some_parent->child_one->some_method(); $this->some_parent->child_two->another_method();

Creating Your Own Drivers

Please read the section of the user guide that discusses how to create your own drivers.

6.1.10 Creating Drivers

Driver Directory and File Structure

Sample driver directory and file structure layout: • /application/libraries/Driver_name – Driver_name.php – drivers

* Driver_name_subclass_1.php * Driver_name_subclass_2.php * Driver_name_subclass_3.php

: In order to maintain compatibility on case-sensitive file systems, the Driver_name directory must be named in the format returned by ucfirst().

6.1. General Topics 35 CodeIgniter Documentation, 3.0-dev

6.1.11 Creating Core System Classes

Every time CodeIgniter runs there are several base classes that are initialized automatically as part of the core frame- work. It is possible, however, to swap any of the core system classes with your own versions or even extend the core versions. Most users will never have any need to do this, but the option to replace or extend them does exist for those who would like to significantly alter the CodeIgniter core.

: Messing with a core system class has a lot of implications, so make sure you know what you are doing before attempting it.

System Class List

The following is a list of the core system files that are invoked every time CodeIgniter runs: • Benchmark • Config • Controller • Exceptions • Hooks • Input • Language • Loader • Log • Output • Router • Security • URI • Utf8

Replacing Core Classes

To use one of your own system classes instead of a default one simply place your version inside your local applica- tion/core/ directory: application/core/some_class.php

If this directory does not exist you can create it. Any file named identically to one from the list above will be used instead of the one normally used. Please note that your class must use CI as a prefix. For example, if your file is named Input.php the class will be named: class CI_Input {

}

36 Chapter 6. CodeIgniter Documentation, 3.0-dev

Extending Core Class

If all you need to do is add some functionality to an existing library - perhaps add a method or two - then it’s overkill to replace the entire library with your version. In this case it’s better to simply extend the class. Extending a class is nearly identical to replacing a class with a couple exceptions: • The class declaration must extend the parent class. • Your new class name and filename must be prefixed with MY_ (this item is configurable. See below.). For example, to extend the native Input class you’ll create a file named application/core/MY_Input.php, and declare your class with: class MY_Input extends CI_Input {

}

: If you need to use a constructor in your class make sure you extend the parent constructor: class MY_Input extends CI_Input {

public function __construct() { parent::__construct(); } }

Tip: Any functions in your class that are named identically to the methods in the parent class will be used instead of the native ones (this is known as “method overriding”). This allows you to substantially alter the CodeIgniter core. If you are extending the Controller core class, then be sure to extend your new class in your application controller’s constructors. class Welcome extends MY_Controller {

public function __construct() { parent::__construct(); }

public function index() { $this->load->view(’welcome_message’); } }

Setting Your Own Prefix

To set your own sub-class prefix, open your application/config/config.php file and look for this item: $config[’subclass_prefix’] = ’MY_’;

Please note that all native CodeIgniter libraries are prefixed with CI_ so DO NOT use that as your prefix.

6.1. General Topics 37 CodeIgniter Documentation, 3.0-dev

6.1.12 Creating Ancillary Classes

In some cases you may want to develop classes that exist apart from your controllers but have the ability to utilize all of CodeIgniter’s resources. This is easily possible as you’ll see. get_instance() get_instance() object of class CI_Controller Any class that you instantiate within your controller methods can access CodeIgniter’s native resources simply by using the get_instance() function. This function returns the main CodeIgniter object. Normally, to call any of the available CodeIgniter methods requires you to use the $this construct: $this->load->helper(’url’); $this->load->library(’session’); $this->config->item(’base_url’); // etc.

$this, however, only works within your controllers, your models, or your views. If you would like to use CodeIgniter’s classes from within your own custom classes you can do so as follows: First, assign the CodeIgniter object to a variable: $CI =& get_instance();

Once you’ve assigned the object to a variable, you’ll use that variable instead of $this: $CI =& get_instance();

$CI->load->helper(’url’); $CI->load->library(’session’); $CI->config->item(’base_url’); // etc.

: You’ll notice that the above get_instance() function is being passed by reference: $CI =& get_instance();

This is very important. Assigning by reference allows you to use the original CodeIgniter object rather than creating a copy of it.

Furthermore, if you’ll be using get_intance() inside anoter class, then it would be better if you assign it to a property. This way, you won’t need to call get_instance() in every single method. Example: class Example {

protected $CI;

// We’ll use a constructor, as you can’t directly call a function // from a property definition. public function __construct() { // Assign the CodeIgniter super-object $this->CI =& get_instance();

38 Chapter 6. CodeIgniter Documentation, 3.0-dev

}

public function foo() { $this->CI->load->helper(’url’); redirect(); }

public function bar() { $this->CI->config_item(’base_url’); }

}

In the above example, both methods foo() and bar() will work after you instantiate the Example class, without the need to call get_instance() in each of them.

6.1.13 Hooks - Extending the Framework Core

CodeIgniter’s Hooks feature provides a means to tap into and modify the inner workings of the framework without hacking the core files. When CodeIgniter runs it follows a specific execution process, diagramed in the Application Flow page. There may be instances, however, where you’d like to cause some action to take place at a particular stage in the execution process. For example, you might want to run a script right before your controllers get loaded, or right after, or you might want to trigger one of your own scripts in some other location.

Enabling Hooks

The hooks feature can be globally enabled/disabled by setting the following item in the application/config/config.php file: $config[’enable_hooks’] = TRUE;

Defining a Hook

Hooks are defined in application/config/hooks.php file. Each hook is specified as an array with this prototype: $hook[’pre_controller’] = array( ’class’ => ’MyClass’, ’function’ => ’Myfunction’, ’filename’ => ’Myclass.php’, ’filepath’ => ’hooks’, ’params’ => array(’beer’, ’wine’, ’snacks’) );

Notes: The array index correlates to the name of the particular hook point you want to use. In the above example the hook point is pre_controller. A list of hook points is found below. The following items should be defined in your associative hook array: • class The name of the class you wish to invoke. If you prefer to use a procedural function instead of a class, leave this item blank. • function The function (or method) name you wish to call.

6.1. General Topics 39 CodeIgniter Documentation, 3.0-dev

• filename The file name containing your class/function. • filepath The name of the directory containing your script. Note: Your script must be located in a directory INSIDE your application/ directory, so the file path is relative to that directory. For example, if your script is located in application/hooks/, you will simply use ‘hooks’ as your filepath. If your script is located in applica- tion/hooks/utilities/ you will use ‘hooks/utilities’ as your filepath. No trailing slash. • params Any parameters you wish to pass to your script. This item is optional.

Multiple Calls to the Same Hook

If want to use the same hook point with more then one script, simply make your array declaration multi-dimensional, like this: $hook[’pre_controller’][] = array( ’class’ => ’MyClass’, ’function’ => ’MyMethod’, ’filename’ => ’Myclass.php’, ’filepath’ => ’hooks’, ’params’ => array(’beer’, ’wine’, ’snacks’) );

$hook[’pre_controller’][] = array( ’class’ => ’MyOtherClass’, ’function’ => ’MyOtherMethod’, ’filename’ => ’Myotherclass.php’, ’filepath’ => ’hooks’, ’params’ => array(’red’, ’yellow’, ’blue’) );

Notice the brackets after each array index: $hook[’pre_controller’][]

This permits you to have the same hook point with multiple scripts. The order you define your array will be the execution order.

Hook Points

The following is a list of available hook points. • pre_system Called very early during system execution. Only the benchmark and hooks class have been loaded at this point. No routing or other processes have happened. • pre_controller Called immediately prior to any of your controllers being called. All base classes, routing, and security checks have been done. • post_controller_constructor Called immediately after your controller is instantiated, but prior to any method calls happening. • post_controller Called immediately after your controller is fully executed. • display_override Overrides the _display() method, used to send the finalized page to the web browser at the end of system execution. This permits you to use your own display methodology. Note that you will need to reference the CI superobject with $this->CI =& get_instance() and then the finalized data will be available by calling $this->CI->output->get_output(). • cache_override Enables you to call your own method instead of the _display_cache() method in the Output Library. This permits you to use your own cache display mechanism.

40 Chapter 6. CodeIgniter Documentation, 3.0-dev

• post_system Called after the final rendered page is sent to the browser, at the end of system execution after the finalized data is sent to the browser.

6.1.14 Auto-loading Resources

CodeIgniter comes with an “Auto-load” feature that permits libraries, helpers, and models to be initialized automat- ically every time the system runs. If you need certain resources globally throughout your application you should consider auto-loading them for convenience. The following items can be loaded automatically: • Classes found in the libraries/ directory • Helper files found in the helpers/ directory • Custom config files found in the config/ directory • Language files found in the system/language/ directory • Models found in the models/ folder To autoload resources, open the application/config/autoload.php file and add the item you want loaded to the autoload array. You’ll find instructions in that file corresponding to each type of item.

: Do not include the file extension (.php) when adding items to the autoload array.

6.1.15 Common Functions

CodeIgniter uses a few functions for its operation that are globally defined, and are available to you at any point. These do not require loading any libraries or helpers. is_php() is_php($version = ‘5.3.0’)

• $version (string) – Version number bool Determines of the PHP version being used is greater than the supplied version number. Example: if (is_php(’5.3’)) { $str = quoted_printable_encode($str); }

Returns boolean TRUE if the installed version of PHP is equal to or greater than the supplied version number. Returns FALSE if the installed version of PHP is lower than the supplied version number. is_really_writable() is_really_writable($file)

6.1. General Topics 41 CodeIgniter Documentation, 3.0-dev

• $file (string) – File path bool is_writable() returns TRUE on Windows servers when you really can’t write to the file as the OS reports to PHP as FALSE only if the read-only attribute is marked. This function determines if a file is actually writable by attempting to write to it first. Generally only recommended on platforms where this information may be unreliable. Example: if (is_really_writable(’file.txt’)) { echo "I could write to this if I wanted to"; } else { echo "File is not writable"; } config_item() config_item($key)

• $key (string) – Config item key mixed The Config Library is the preferred way of accessing configuration information, however config_item() can be used to retrieve single keys. See Config Library documentation for more information. show_error() show_error($message, $status_code, $heading = ‘An Error Was Encountered’)

• $message (mixed) – Error message • $status_code (int) – HTTP Response status code • $heading (string) – Error page heading void This function calls CI_Exception::show_error(). For more info, please see the Error Handling documenta- tion. show_404() show_404($page = ‘’, $log_error = TRUE)

• $page (string) – URI string • $log_error (bool) – Whether to log the error void

42 Chapter 6. CodeIgniter Documentation, 3.0-dev

This function calls CI_Exception::show_404(). For more info, please see the Error Handling documentation.

log_message()

log_message($level, $message)

• $level (string) – Log level: ‘error’, ‘debug’ or ‘info’ • $message (string) – Message to log void This function is an alias for CI_Log::write_log(). For more info, please see the Error Handling documentation.

set_status_header()

set_status_header($code, $text = ‘’)

• $code (int) – HTTP Reponse status code • $text (string) – A custom message to set with the status code void Permits you to manually set a server status header. Example: set_status_header(401); // Sets the header as: Unauthorized

See here for a full list of headers.

remove_invisible_characters()

remove_invisible_characters($str, $url_encoded = TRUE)

• $str (string) – Input string • $url_encoded (bool) – Whether to remove URL-encoded characters as well string This function prevents inserting NULL characters between ASCII characters, like \0script. Example: remove_invisible_characters(’Java\\0script’); // Returns: ’Javascript’

html_escape()

html_escape($var)

• $var (mixed) – Variable to escape (string or array)

6.1. General Topics 43 CodeIgniter Documentation, 3.0-dev

mixed This function acts as an alias for PHP’s native htmlspecialchars() function, with the advantage of being able to accept an array of strings. It is useful in preventing Cross Site Scripting (XSS).

get_mimes()

get_mimes() array This function returns a reference to the MIMEs array from application/config/mimes.php.

is_https()

is_https() bool Returns TRUE if a secure (HTTPS) connection is used and FALSE in any other case (including non-HTTP requests).

is_cli()

is_cli() bool Returns TRUE if the application is run through the command line and FALSE if not.

: This function checks both if the PHP_SAPI value is ‘cli’ or if the STDIN constant is defined.

function_usable()

function_usable($function_name)

• $function_name (string) – Function name bool Returns TRUE if a function exists and is usable, FALSE otherwise. This function runs a function_exists() check and if the Suhosin extension is loaded, checks if it doesn’t disable the function being checked. It is useful if you want to check for the availability of functions such as eval() and exec(), which are dangerous and might be disabled on servers with highly restrictive security policies.

6.1.16 URI Routing

Typically there is a one-to-one relationship between a URL string and its corresponding controller class/method. The segments in a URI normally follow this pattern:

44 Chapter 6. CodeIgniter Documentation, 3.0-dev

example.com/class/function/id/

In some instances, however, you may want to remap this relationship so that a different class/method can be called instead of the one corresponding to the URL. For example, let’s say you want your URLs to have this prototype: example.com/product/1/ example.com/product/2/ example.com/product/3/ example.com/product/4/

Normally the second segment of the URL is reserved for the method name, but in the example above it instead has a product ID. To overcome this, CodeIgniter allows you to remap the URI handler.

Setting your own routing rules

Routing rules are defined in your application/config/routes.php file. In it you’ll see an array called $route that per- mits you to specify your own routing criteria. Routes can either be specified using wildcards or Regular Expressions.

Wildcards

A typical wildcard route might look something like this: $route[’product/:num’] = ’catalog/product_lookup’;

In a route, the array key contains the URI to be matched, while the array value contains the destination it should be re-routed to. In the above example, if the literal word “product” is found in the first segment of the URL, and a number is found in the second segment, the “catalog” class and the “product_lookup” method are instead used. You can match literal values or you can use two wildcard types: (:num) will match a segment containing only numbers. (:any) will match a segment containing any character (except for ‘/’, which is the segment delimiter).

: Wildcards are actually aliases for regular expressions, with :any being translated to [^/]+ and :num to [0-9]+, respectively.

: Routes will run in the order they are defined. Higher routes will always take precedence over lower ones.

: Route rules are not filters! Setting a rule of e.g. ‘foo/bar/(:num)’ will not prevent controller Foo and method bar to be called with a non-numeric value if that is a valid route.

Examples

Here are a few routing examples: $route[’journals’] = ’blogs’;

A URL containing the word “journals” in the first segment will be remapped to the “blogs” class. $route[’blog/joe’] = ’blogs/users/34’;

6.1. General Topics 45 CodeIgniter Documentation, 3.0-dev

A URL containing the segments blog/joe will be remapped to the “blogs” class and the “users” method. The ID will be set to “34”. $route[’product/(:any)’] = ’catalog/product_lookup’;

A URL with “product” as the first segment, and anything in the second will be remapped to the “catalog” class and the “product_lookup” method. $route[’product/(:num)’] = ’catalog/product_lookup_by_id/$1’;

A URL with “product” as the first segment, and a number in the second will be remapped to the “catalog” class and the “product_lookup_by_id” method passing in the match as a variable to the method.

: Do not use leading/trailing slashes.

Regular Expressions

If you prefer you can use regular expressions to define your routing rules. Any valid regular expression is allowed, as are back-references.

: If you use back-references you must use the dollar syntax rather than the double backslash syntax.

A typical RegEx route might look something like this: $route[’products/([a-z]+)/(\d+)’] = ’$1/id_$2’;

In the above example, a URI similar to products/shirts/123 would instead call the “shirts” controller class and the “id_123” method. With regular expressions, you can also catch a segment containing a forward slash (‘/’), which would usually represent the delimiter between multiple segments. For example, if a user accesses a password protected area of your web application and you wish to be able to redirect them back to the same page after they log in, you may find this example useful: $route[’login/(.+)’] = ’auth/login/$1’;

That will call the “auth” controller class and its login() method, passing everything contained in the URI after login/ as a parameter. For those of you who don’t know regular expressions and want to learn more about them, regular-expressions.info might be a good starting point.

: You can also mix and match wildcards with regular expressions.

Callbacks

If you are using PHP >= 5.3 you can use callbacks in place of the normal routing rules to process the back-references. Example: $route[’products/([a-zA-Z]+)/edit/(\d+)’] = function ($product_type, $id) { return ’catalog/product_edit/’ . strtolower($product_type) . ’/’ . $id; };

46 Chapter 6. CodeIgniter Documentation, 3.0-dev

Using HTTP verbs in routes

It is possible to use HTTP verbs (request method) to define your routing rules. This is particularly useful when building RESTful applications. You can use standard HTTP verbs (GET, PUT, POST, DELETE, PATCH) or a custom one such (e.g. PURGE). HTTP verb rules are case-insensitive. All you need to do is to add the verb as an array key to your route. Example: $route[’products’][’put’] = ’product/insert’;

In the above example, a PUT request to URI “products” would call the Product::insert() controller method. $route[’products/(:num)’][’DELETE’] = ’product/delete/$1’;

A DELETE request to URL with “products” as first the segment and a number in the second will be mapped to the Product::delete() method, passing the numeric value as the first parameter. Using HTTP verbs is of course, optional.

Reserved Routes

There are three reserved routes: $route[’default_controller’] = ’welcome’;

This route indicates which controller class should be loaded if the URI contains no data, which will be the case when people load your root URL. In the above example, the “welcome” class would be loaded. You are encouraged to always have a default route otherwise a 404 page will appear by default. $route[’404_override’] = ’’;

This route indicates which controller class should be loaded if the requested controller is not found. It will override the default 404 error page. It won’t affect to the show_404() function, which will continue loading the default error_404.php file at application/views/errors/error_404.php. $route[’translate_uri_dashes’] = FALSE;

As evident by the boolean value, this is not exactly a route. This option enables you to automatically replace dashes (‘-‘) with underscores in the controller and method URI segments, thus saving you additional route entries if you need to do that. This is required, because the dash isn’t a valid class or method name character and would cause a fatal error if you try to use it.

: The reserved routes must come before any wildcard or regular expression routes.

6.1.17 Error Handling

CodeIgniter lets you build error reporting into your applications using the functions described below. In addition, it has an error logging class that permits error and debugging messages to be saved as text files.

: By default, CodeIgniter displays all PHP errors. You might wish to change this behavior once your development is complete. You’ll find the error_reporting() function located at the top of your main index.php file. Disabling error reporting will NOT prevent log files from being written if there are errors.

Unlike most systems in CodeIgniter, the error functions are simple procedural interfaces that are available globally throughout the application. This approach permits error messages to get triggered without having to worry about class/function scoping.

6.1. General Topics 47 CodeIgniter Documentation, 3.0-dev

CodeIgniter also returns a status code whenever a portion of the core calls exit(). This exit status code is separate from the HTTP status code, and serves as a notice to other processes that may be watching of whether the script completed successfully, or if not, what kind of problem it encountered that caused it to abort. These values are defined in application/config/constants.php. While exit status codes are most useful in CLI settings, returning the proper code helps server keep track of your scripts and the health of your application. The following functions let you generate errors:

show_error()

show_error($message, $status_code, $heading = ‘An Error Was Encountered’)

• $message (mixed) – Error message • $status_code (int) – HTTP Response status code • $heading (string) – Error page heading void This function will display the error message supplied to it using the following error template: application/views/errors/error_general.php

The optional parameter $status_code determines what HTTP status code should be sent with the error. If $status_code is less than 100, the HTTP status code will be set to 500, and the exit status code will be set to $status_code + EXIT__AUTO_MIN. If that value is larger than EXIT__AUTO_MAX, or if $status_code is 100 or higher, the exit status code will be set to EXIT_ERROR. You can check in application/config/constants.php for more detail.

show_404()

show_404($page = ‘’, $log_error = TRUE)

• $page (string) – URI string • $log_error (bool) – Whether to log the error void This function will display the 404 error message supplied to it using the following error template: application/views/errors/error_404.php

The function expects the string passed to it to be the file path to the page that isn’t found. The exit status code will be set to EXIT_UNKNOWN_FILE. Note that CodeIgniter automatically shows 404 messages if controllers are not found. CodeIgniter automatically logs any show_404() calls. Setting the optional second parameter to FALSE will skip logging.

log_message()

log_message($level, $message, $php_error = FALSE)

• $level (string) – Log level: ‘error’, ‘debug’ or ‘info’

48 Chapter 6. CodeIgniter Documentation, 3.0-dev

• $message (string) – Message to log • $php_error (bool) – Whether we’re logging a native PHP error message void This function lets you write messages to your log files. You must supply one of three “levels” in the first parameter, indicating what type of message it is (debug, error, info), with the message itself in the second parameter. Example: if ($some_var == ’’) { log_message(’error’, ’Some variable did not contain a value.’); } else { log_message(’debug’, ’Some variable was correctly set’); } log_message(’info’, ’The purpose of some variable is to provide some value.’);

There are three message types: 1. Error Messages. These are actual errors, such as PHP errors or user errors. 2. Debug Messages. These are messages that assist in debugging. For example, if a class has been initialized, you could log this as debugging info. 3. Informational Messages. These are the lowest priority messages, simply giving information regarding some process. CodeIgniter doesn’t natively generate any info messages but you may want to in your application.

: In order for the log file to actually be written, the logs directory must be writable. In addition, you must set the “threshold” for logging in application/config/config.php. You might, for example, only want error messages to be logged, and not the other two types. If you set it to zero logging will be disabled.

6.1.18 Web Page Caching

CodeIgniter lets you cache your pages in order to achieve maximum performance. Although CodeIgniter is quite fast, the amount of dynamic information you display in your pages will correlate directly to the server resources, memory, and processing cycles utilized, which affect your page load speeds. By caching your pages, since they are saved in their fully rendered state, you can achieve performance that nears that of static web pages.

How Does Caching Work?

Caching can be enabled on a per-page basis, and you can set the length of time that a page should remain cached before being refreshed. When a page is loaded for the first time, the cache file will be written to your application/cache folder. On subsequent page loads the cache file will be retrieved and sent to the requesting user’s browser. If it has expired, it will be deleted and refreshed before being sent to the browser.

Enabling Caching

To enable caching, put the following tag in any of your controller methods:

6.1. General Topics 49 CodeIgniter Documentation, 3.0-dev

$this->output->cache($n);

Where $n is the number of minutes you wish the page to remain cached between refreshes. The above tag can go anywhere within a method. It is not affected by the order that it appears, so place it wherever it seems most logical to you. Once the tag is in place, your pages will begin being cached.

: Because of the way CodeIgniter stores content for output, caching will only work if you are generating display for your controller with a view.

: Before the cache files can be written you must set the file permissions on your application/cache/ directory such that it is writable.

Deleting Caches

If you no longer wish to cache a file you can remove the caching tag and it will no longer be refreshed when it expires.

: Removing the tag will not delete the cache immediately. It will have to expire normally.

If you need to manually delete the cache, you can use the delete_cache() method: // Deletes cache for the currently requested URI $this->output->delete_cache();

// Deletes cache for /foo/bar $this->output->delete_cache(’/foo/bar’);

6.1.19 Profiling Your Application

The Profiler Class will display benchmark results, queries you have run, and $_POST data at the bottom of your pages. This information can be useful during development in order to help with debugging and optimization.

Initializing the Class

: This class does NOT need to be initialized. It is loaded automatically by the Output Library if profiling is enabled as shown below.

Enabling the Profiler

To enable the profiler place the following line anywhere within your Controller methods: $this->output->enable_profiler(TRUE);

When enabled a report will be generated and inserted at the bottom of your pages. To disable the profiler you will use: $this->output->enable_profiler(FALSE);

50 Chapter 6. CodeIgniter Documentation, 3.0-dev

Setting Benchmark Points

In order for the Profiler to compile and display your benchmark data you must name your mark points using specific syntax. Please read the information on setting Benchmark points in the Benchmark Library page.

Enabling and Disabling Profiler Sections

Each section of Profiler data can be enabled or disabled by setting a corresponding config variable to TRUE or FALSE. This can be done one of two ways. First, you can set application wide defaults with the application/config/profiler.php config file. Example: $config[’config’] = FALSE; $config[’queries’] = FALSE;

In your controllers, you can override the defaults and config file values by calling the set_profiler_sections() method of the Output Library: $sections = array( ’config’ => TRUE, ’queries’ => TRUE );

$this->output->set_profiler_sections($sections);

Available sections and the array key used to access them are described in the table below. Key Description Default benchmarks Elapsed time of Benchmark points and total execution time TRUE config CodeIgniter Config variables TRUE controller_info The Controller class and method requested TRUE get Any GET data passed in the request TRUE http_headers The HTTP headers for the current request TRUE memory_usage Amount of memory consumed by the current request, in bytes TRUE post Any POST data passed in the request TRUE queries Listing of all database queries executed, including execution time TRUE uri_string The URI of the current request TRUE session_data Data stored in the current session TRUE query_toggle_count The number of queries after which the query block will default to hidden. 25

6.1.20 Running via the CLI

As well as calling an applications Controllers via the URL in a browser they can also be loaded via the command-line interface (CLI).

Page Contents • Running via the CLI – What is the CLI? – Why run via the command-line? – Let’s try it: Hello World! – That’s it!

6.1. General Topics 51 CodeIgniter Documentation, 3.0-dev

What is the CLI?

The command-line interface is a text-based method of interacting with computers. For more information, check the Wikipedia article.

Why run via the command-line?

There are many reasons for running CodeIgniter from the command-line, but they are not always obvious. • Run your cron-jobs without needing to use wget or curl • Make your cron-jobs inaccessible from being loaded in the URL by checking the return value of is_cli(). • Make interactive “tasks” that can do things like set permissions, prune cache folders, run backups, etc. • Integrate with other applications in other languages. For example, a random C++ script could call one command and run code in your models!

Let’s try it: Hello World!

Let’s create a simple controller so you can see it in action. Using your text editor, create a file called Tools.php, and put the following code in it:

public function message($to = ’World’) { echo "Hello {$to}!".PHP_EOL; } }

Then save the file to your application/controllers/ folder. Now normally you would visit the your site using a URL similar to this: example.com/index.php/tools/message/to

Instead, we are going to open Terminal in Mac/Linux or go to Run > “cmd” in Windows and navigate to our CodeIgniter project. $ cd /path/to/project; $ php index.php tools message

If you did it right, you should see Hello World! printed. $ php index.php tools message "John Smith"

Here we are passing it a argument in the same way that URL parameters work. “John Smith” is passed as a argument and output is: Hello John Smith!

That’s it!

That, in a nutshell, is all there is to know about controllers on the command line. Remember that this is just a normal controller, so routing and _remap() works fine.

52 Chapter 6. CodeIgniter Documentation, 3.0-dev

6.1.21 Managing your Applications

By default it is assumed that you only intend to use CodeIgniter to manage one application, which you will build in your application/ directory. It is possible, however, to have multiple sets of applications that share a single CodeIgniter installation, or even to rename or relocate your application directory.

Renaming the Application Directory

If you would like to rename your application directory you may do so as long as you open your main index.php file and set its name using the $application_folder variable: $application_folder = ’application’;

Relocating your Application Directory

It is possible to move your application directory to a different location on your server than your web root. To do so open your main index.php and set a full server path in the $application_folder variable: $application_folder = ’/path/to/your/application’;

Running Multiple Applications with one CodeIgniter Installation

If you would like to share a common CodeIgniter installation to manage several different applications simply put all of the directories located inside your application directory into their own sub-directory. For example, let’s say you want to create two applications, named “foo” and “bar”. You could structure your applica- tion directories like this: applications/foo/ applications/foo/config/ applications/foo/controllers/ applications/foo/errors/ applications/foo/libraries/ applications/foo/models/ applications/foo/views/ applications/bar/ applications/bar/config/ applications/bar/controllers/ applications/bar/errors/ applications/bar/libraries/ applications/bar/models/ applications/bar/views/

To select a particular application for use requires that you open your main index.php file and set the $application_folder variable. For example, to select the “foo” application for use you would do this: $application_folder = ’applications/foo’;

: Each of your applications will need its own index.php file which calls the desired application. The index.php file can be named anything you want.

6.1. General Topics 53 CodeIgniter Documentation, 3.0-dev

6.1.22 Handling Multiple Environments

Developers often desire different system behavior depending on whether an application is running in a development or production environment. For example, verbose error output is something that would be useful while developing an application, but it may also pose a security issue when “live”.

The ENVIRONMENT Constant

By default, CodeIgniter comes with the environment constant set to use the value provided in $_SERVER[’CI_ENV’], otherwise defaults to ‘development’. At the top of index.php, you will see: define(’ENVIRONMENT’, isset($_SERVER[’CI_ENV’]) ? $_SERVER[’CI_ENV’] : ’development’);

This server variable can be set in your .htaccess file, or Apache config using SetEnv. Alternative methods are available for nginx and other servers, or you can remove this logic entirely and set the constant based on the HTTP_HOST or IP. In addition to affecting some basic framework behavior (see the next section), you may use this constant in your own development to differentiate between which environment you are running in.

Effects On Default Framework Behavior

There are some places in the CodeIgniter system where the ENVIRONMENT constant is used. This section describes how default framework behavior is affected.

Error Reporting

Setting the ENVIRONMENT constant to a value of ‘development’ will cause all PHP errors to be rendered to the browser when they occur. Conversely, setting the constant to ‘production’ will disable all error output. Disabling error reporting in production is a good security practice.

Configuration Files

Optionally, you can have CodeIgniter load environment-specific configuration files. This may be useful for managing things like differing API keys across multiple environments. This is described in more detail in the environment section of the Config Class documentation.

6.1.23 Alternate PHP Syntax for View Files

If you do not utilize CodeIgniter’s template engine, you’ll be using pure PHP in your View files. To minimize the PHP code in these files, and to make it easier to identify the code blocks it is recommended that you use alternative syntax for control structures and short tag echo statements. If you are not familiar with this syntax, it allows you to eliminate the braces from your code, and eliminate “echo” statements.

Automatic Short Tag Support

: If you find that the syntax described in this page does not work on your server it might be that “short tags” are disabled in your PHP ini file. CodeIgniter will optionally rewrite short tags on-the-fly, allowing you to use that syntax even if your server doesn’t support it. This feature can be enabled in your config/config.php file.

54 Chapter 6. CodeIgniter Documentation, 3.0-dev

Please note that if you do use this feature, if PHP errors are encountered in your view files, the error message and line number will not be accurately shown. Instead, all errors will be shown as eval() errors.

Alternative Echos

Normally to echo, or print out a variable you would do this:

With the alternative syntax you can instead do it this way:

Alternative Control Structures

Controls structures, like if, for, foreach, and while can be written in a simplified format as well. Here is an example using foreach:

Notice that there are no braces. Instead, the end brace is replaced with endforeach. Each of the control structures listed above has a similar closing syntax: endif, endfor, endforeach, and endwhile Also notice that instead of using a semicolon after each structure (except the last one), there is a colon. This is important! Here is another example, using if/elseif/else. Notice the colons:

Hi Sally

Hi Joe

Hi unknown user

6.1.24 Security

This page describes some “best practices” regarding web security, and details CodeIgniter’s internal security features.

6.1. General Topics 55 CodeIgniter Documentation, 3.0-dev

URI Security

CodeIgniter is fairly restrictive regarding which characters it allows in your URI strings in order to help minimize the possibility that malicious data can be passed to your application. URIs may only contain the following: • Alpha-numeric text (latin characters only) • Tilde: ~ • Percent sign: % • Period: . • Colon: : • Underscore: _ • Dash: - • Space

Register_globals

During system initialization all global variables are unset, except those found in the $_GET, $_POST, and $_COOKIE arrays. The unsetting routine is effectively the same as register_globals = off. display_errors

In production environments, it is typically desirable to “disable” PHP’s error reporting by setting the internal dis- play_errors flag to a value of 0. This disables native PHP errors from being rendered as output, which may potentially contain sensitive information. Setting CodeIgniter’s ENVIRONMENT constant in index.php to a value of ‘production’ will turn off these errors. In development mode, it is recommended that a value of ‘development’ is used. More information about differentiating between environments can be found on the Handling Environments page. magic_quotes_runtime

The magic_quotes_runtime directive is turned off during system initialization so that you don’t have to remove slashes when retrieving data from your database.

Best Practices

Before accepting any data into your application, whether it be POST data from a form submission, COOKIE data, URI data, XML-RPC data, or even data from the SERVER array, you are encouraged to practice this three step approach: 1. Filter the data as if it were tainted. 2. Validate the data to ensure it conforms to the correct type, length, size, etc. (sometimes this step can replace step one) 3. Escape the data before submitting it into your database. CodeIgniter provides the following functions to assist in this process:

56 Chapter 6. CodeIgniter Documentation, 3.0-dev

XSS Filtering

CodeIgniter comes with a Cross Site Scripting filter. This filter looks for commonly used techniques to embed mali- cious JavaScript into your data, or other types of code that attempt to hijack cookies or do other malicious things. The XSS Filter is described here.

Validate the data

CodeIgniter has a Form Validation Library that assists you in validating, filtering, and prepping your data.

Escape all data before database insertion

Never insert information into your database without escaping it. Please see the section that discusses database queries for more information.

Hide your files

Another good security practice is to only leave your index.php and “assets” (e.g. .js, css and image files) under your server’s webroot directory (most commonly named “htdocs/”). These are the only files that you would need to be accessible from the web. Allowing your visitors to see anything else would potentially allow them to access sensitive data, execute scripts, etc. If you’re not allowed to do that, you can try using a .htaccess file to restrict access to those resources. CodeIgniter will have an index.html file in all of its directories in an attempt to hide some of this data, but have it in mind that this is not enough to prevent a serious attacker.

6.1.25 PHP Style Guide

The following page describes the coding styles adhered to when contributing to the development of CodeIgniter. There is no requirement to use these styles in your own CodeIgniter application, though they are recommended.

6.1. General Topics 57 CodeIgniter Documentation, 3.0-dev

Table of Contents • PHP Style Guide – File Format * TextMate * BBEdit – PHP Closing Tag – File Naming – Class and Method Naming – Variable Names – Commenting – Constants – TRUE, FALSE, and NULL – Logical Operators – Comparing Return Values and Typecasting – Debugging Code – Whitespace in Files – Compatibility – One File per Class – Whitespace – Line Breaks – Code Indenting – Bracket and Parenthetic Spacing – Localized Text – Private Methods and Variables – PHP Errors – Short Open Tags – One Statement Per Line – Strings – SQL Queries – Default Function Arguments

File Format

Files should be saved with Unicode (UTF-8) encoding. The BOM should not be used. Unlike UTF-16 and UTF-32, there’s no byte order to indicate in a UTF-8 encoded file, and the BOM can have a negative side effect in PHP of sending output, preventing the application from being able to set its own headers. Unix line endings should be used (LF). Here is how to apply these settings in some of the more common text editors. Instructions for your text editor may vary; check your text editor’s documentation.

TextMate

1. Open the Application Preferences 2. Click Advanced, and then the “Saving” tab 3. In “File Encoding”, select “UTF-8 (recommended)” 4. In “Line Endings”, select “LF (recommended)” 5. Optional: Check “Use for existing files as well” if you wish to modify the line endings of files you open to your new preference.

58 Chapter 6. CodeIgniter Documentation, 3.0-dev

BBEdit

1. Open the Application Preferences 2. Select “Text Encodings” on the left. 3. In “Default text encoding for new documents”, select “Unicode (UTF-8, no BOM)” 4. Optional: In “If file’s encoding can’t be guessed, use”, select “Unicode (UTF-8, no BOM)” 5. Select “Text Files” on the left. 6. In “Default line breaks”, select “Mac OS X and Unix (LF)”

PHP Closing Tag

The PHP closing tag on a PHP document ?> is optional to the PHP parser. However, if used, any whitespace following the closing tag, whether introduced by the developer, user, or an FTP application, can cause unwanted output, PHP errors, or if the latter are suppressed, blank pages. For this reason, all PHP files should OMIT the closing PHP tag, and instead use a comment block to mark the end of file and its location relative to the application root. This allows you to still identify a file as being complete and not truncated. INCORRECT:

?>

CORRECT:

/* End of file Myfile.php */ /* Location: ./system/modules/mymodule/myfile.php */

: There should be no empty line or newline character(s) following the closing comments. If you happen to see one when submitting a pull request, please check your IDE settings and fix it.

File Naming

Class files must be named in a Ucfirst-like manner, while any other file name (configurations, views, generic scripts, etc.) should be in all lowercase. INCORRECT: somelibrary.php someLibrary.php SOMELIBRARY.php Some_Library.php

Application_config.php Application_Config.php applicationConfig.php

6.1. General Topics 59 CodeIgniter Documentation, 3.0-dev

CORRECT: Somelibrary.php Some_library.php

applicationconfig.php application_config.php

Furthermore, class file names should match the name of the class itself. For example, if you have a class named Myclass, then its filename must be Myclass.php.

Class and Method Naming

Class names should always start with an uppercase letter. Multiple words should be separated with an underscore, and not CamelCased. INCORRECT: class superclass class SuperClass

CORRECT: class Super_class

class Super_class {

public function __construct() {

} }

Class methods should be entirely lowercased and named to clearly indicate their function, preferably including a verb. Try to avoid overly long and verbose names. Multiple words should be separated with an underscore. INCORRECT: function fileproperties() // not descriptive and needs underscore separator function fileProperties() // not descriptive and uses CamelCase function getfileproperties() // Better! But still missing underscore separator function getFileProperties() // uses CamelCase function get_the_file_properties_from_the_file() // wordy

CORRECT: function get_file_properties() // descriptive, underscore separator, and all lowercase letters

Variable Names

The guidelines for variable naming are very similar to those used for class methods. Variables should contain only lowercase letters, use underscore separators, and be reasonably named to indicate their purpose and contents. Very short, non-word variables should only be used as iterators in for() loops. INCORRECT:

60 Chapter 6. CodeIgniter Documentation, 3.0-dev

$j = ’foo’; // single letter variables should only be used in for() loops $Str // contains uppercase letters $bufferedText // uses CamelCasing, and could be shortened without losing semantic meaning $groupid // multiple words, needs underscore separator $name_of_last_city_used // too long

CORRECT: for ($j = 0; $j < 10; $j++) $str $buffer $group_id $last_city

Commenting

In general, code should be commented prolifically. It not only helps describe the flow and intent of the code for less experienced programmers, but can prove invaluable when returning to your own code months down the line. There is not a required format for comments, but the following are recommended. DocBlock style comments preceding class, method, and property declarations so they can be picked up by IDEs:

/** * Super Class * * @package Package Name * @subpackage Subpackage * @category Category * @author Author Name * @link http://example.com */ class Super_class {

/** * Encodes string for use in XML * * @param string $str Input string * @return string */ function xml_encode($str)

/** * Data for class manipulation * * @var array */ public $data = array();

Use single line comments within code, leaving a blank line between large comment blocks and code. // break up the string by newlines $parts = explode("\n", $str);

// A longer comment that needs to give greater detail on what is // occurring and why can use multiple single-line comments. Try to // keep the width reasonable, around 70 characters is the easiest to // read. Don’t hesitate to link to permanent external resources // that may provide greater detail:

6.1. General Topics 61 CodeIgniter Documentation, 3.0-dev

// // http://example.com/information_about_something/in_particular/

$parts = $this->foo($parts);

Constants

Constants follow the same guidelines as do variables, except constants should always be fully uppercase. Always use CodeIgniter constants when appropriate, i.e. SLASH, LD, RD, PATH_CACHE, etc. INCORRECT: myConstant // missing underscore separator and not fully uppercase N // no single-letter constants S_C_VER // not descriptive $str = str_replace(’{foo}’, ’bar’, $str); // should use LD and RD constants

CORRECT: MY_CONSTANT NEWLINE SUPER_CLASS_VERSION $str = str_replace(LD.’foo’.RD, ’bar’, $str);

TRUE, FALSE, and NULL

TRUE, FALSE, and NULL keywords should always be fully uppercase. INCORRECT: if ($foo == true) $bar = false; function foo($bar = null)

CORRECT: if ($foo == TRUE) $bar = FALSE; function foo($bar = NULL)

Logical Operators

Use of the || “or” comparison operator is discouraged, as its clarity on some output devices is low (looking like the number 11, for instance). && is preferred over AND but either are acceptable, and a space should always precede and follow !. INCORRECT:

if ($foo || $bar) if ($foo AND $bar) // okay but not recommended for common syntax highlighting applications if (!$foo) if (! is_array($foo))

CORRECT:

62 Chapter 6. CodeIgniter Documentation, 3.0-dev

if ($foo OR $bar) if ($foo && $bar) // recommended if ( ! $foo) if ( ! is_array($foo))

Comparing Return Values and Typecasting

Some PHP functions return FALSE on failure, but may also have a valid return value of “” or 0, which would eval- uate to FALSE in loose comparisons. Be explicit by comparing the variable type when using these return values in conditionals to ensure the return value is indeed what you expect, and not a value that has an equivalent loose-type evaluation. Use the same stringency in returning and checking your own variables. Use === and !== as necessary. INCORRECT: // If ’foo’ is at the beginning of the string, strpos will return a 0, // resulting in this conditional evaluating as TRUE if (strpos($str, ’foo’) == FALSE)

CORRECT: if (strpos($str, ’foo’) === FALSE)

INCORRECT: function build_string($str = "") { if ($str == "") // uh-oh! What if FALSE or the integer 0 is passed as an argument? {

} }

CORRECT: function build_string($str = "") { if ($str === "") {

} }

See also information regarding typecasting, which can be quite useful. Typecasting has a slightly different effect which may be desirable. When casting a variable as a string, for instance, NULL and boolean FALSE variables become empty strings, 0 (and other numbers) become strings of digits, and boolean TRUE becomes “1”: $str = (string) $str; // cast $str as a string

Debugging Code

Do not leave debugging code in your submissions, even when commented out. Things such as var_dump(), print_r(), die()/exit() should not be included in your code unless it serves a specific purpose other than debugging.

6.1. General Topics 63 CodeIgniter Documentation, 3.0-dev

Whitespace in Files

No whitespace can precede the opening PHP tag or follow the closing PHP tag. Output is buffered, so whitespace in your files can cause output to begin before CodeIgniter outputs its content, leading to errors and an inability for CodeIgniter to send proper headers.

Compatibility

CodeIgniter requires a minimum PHP version of 5.2.4. Your code must either be compatible with this minimum re- quirement, provide a suitable fallback, or be an optional feature that dies quietly without affecting a user’s application. Additionally, do not use PHP functions that require non-default libraries to be installed unless your code contains an alternative method when the function is not available.

One File per Class

Use separate files for each class, unless the classes are closely related. An example of a CodeIgniter file that contains multiple classes is the Xmlrpc library file.

Whitespace

Use tabs for whitespace in your code, not spaces. This may seem like a small thing, but using tabs instead of whitespace allows the developer looking at your code to have indentation at levels that they prefer and customize in whatever application they use. And as a side benefit, it results in (slightly) more compact files, storing one tab character versus, say, four space characters.

Line Breaks

Files must be saved with Unix line breaks. This is more of an issue for developers who work in Windows, but in any case ensure that your text editor is setup to save files with Unix line breaks.

Code Indenting

Use Allman style indenting. With the exception of Class declarations, braces are always placed on a line by themselves, and indented at the same level as the control statement that “owns” them. INCORRECT: function foo($bar) { // ... } foreach ($arr as $key => $val) { // ... } if ($foo == $bar) { // ... } else { // ... } for ($i = 0; $i < 10; $i++)

64 Chapter 6. CodeIgniter Documentation, 3.0-dev

{ for ($j = 0; $j < 10; $j++) { // ... } } try { // ... } catch() { // ... }

CORRECT: function foo($bar) { // ... } foreach ($arr as $key => $val) { // ... } if ($foo == $bar) { // ... } else { // ... } for ($i = 0; $i < 10; $i++) { for ($j = 0; $j < 10; $j++) { // ... } } try { // ... } catch() { // ... }

Bracket and Parenthetic Spacing

In general, parenthesis and brackets should not use any additional spaces. The exception is that a space should always follow PHP control structures that accept arguments with parenthesis (declare, do-while, elseif, for, foreach, if, switch, while), to help distinguish them from functions and increase readability.

6.1. General Topics 65 CodeIgniter Documentation, 3.0-dev

INCORRECT: $arr[ $foo ] = ’foo’;

CORRECT: $arr[$foo] = ’foo’; // no spaces around array keys

INCORRECT: function foo ( $bar ) {

}

CORRECT: function foo($bar) // no spaces around parenthesis in function declarations {

}

INCORRECT: foreach( $query->result() as $row )

CORRECT: foreach ($query->result() as $row) // single space following PHP control structures, but not in interior parenthesis

Localized Text

CodeIgniter libraries should take advantage of corresponding language files whenever possible. INCORRECT: return "Invalid Selection";

CORRECT: return $this->lang->line(’invalid_selection’);

Private Methods and Variables

Methods and variables that are only accessed internally, such as utility and helper functions that your public methods use for code abstraction, should be prefixed with an underscore. public function convert_text() private function _convert_text()

PHP Errors

Code must run error free and not rely on warnings and notices to be hidden to meet this requirement. For instance, never access a variable that you did not set yourself (such as $_POST array keys) without first checking to see that it isset(). Make sure that your dev environment has error reporting enabled for ALL users, and that display_errors is enabled in the PHP environment. You can check this setting with:

66 Chapter 6. CodeIgniter Documentation, 3.0-dev

if (ini_get(’display_errors’) == 1) { exit "Enabled"; }

On some servers where display_errors is disabled, and you do not have the ability to change this in the php.ini, you can often enable it with: ini_set(’display_errors’, 1);

: Setting the display_errors setting with ini_set() at runtime is not identical to having it enabled in the PHP environment. Namely, it will not have any effect if the script has fatal errors.

Short Open Tags

Always use full PHP opening tags, in case a server does not have short_open_tag enabled. INCORRECT:

CORRECT:

: PHP 5.4 will always have the

One Statement Per Line

Never combine statements on one line. INCORRECT: $foo = ’this’; $bar = ’that’; $bat = str_replace($foo, $bar, $bag);

CORRECT: $foo = ’this’; $bar = ’that’; $bat = str_replace($foo, $bar, $bag);

Strings

Always use single quoted strings unless you need variables parsed, and in cases where you do need variables parsed, use braces to prevent greedy token parsing. You may also use double-quoted strings if the string contains single quotes, so you do not have to use escape characters. INCORRECT: "My String" // no variable parsing, so no use for double quotes "My string $foo" // needs braces ’SELECT foo FROM bar WHERE baz = \’bag\’’ // ugly

6.1. General Topics 67 CodeIgniter Documentation, 3.0-dev

CORRECT: ’My String’ "My string {$foo}" "SELECT foo FROM bar WHERE baz = ’bag’"

SQL Queries

SQL keywords are always capitalized: SELECT, INSERT, UPDATE, WHERE, AS, JOIN, ON, IN, etc. Break up long queries into multiple lines for legibility, preferably breaking for each clause. INCORRECT: // keywords are lowercase and query is too long for // a single line (... indicates continuation of line) $query = $this->db->query("select foo, bar, baz, foofoo, foobar as raboof, foobaz from exp_pre_email_addresses ...where foo != ’oof’ and baz != ’zab’ order by foobaz limit 5, 100");

CORRECT: $query = $this->db->query("SELECT foo, bar, baz, foofoo, foobar AS raboof, foobaz FROM exp_pre_email_addresses WHERE foo != ’oof’ AND baz != ’zab’ ORDER BY foobaz LIMIT 5, 100");

Default Function Arguments

Whenever appropriate, provide function argument defaults, which helps prevent PHP errors with mistaken calls and provides common fallback values which can save a few lines of code. Example: function foo($bar = ’’, $baz = FALSE)

68 Chapter 6. CHAPTER 7

7.1 Libraries

7.1.1 Benchmarking Class

CodeIgniter has a Benchmarking class that is always active, enabling the time difference between any two marked points to be calculated.

: This class is initialized automatically by the system so there is no need to do it manually.

In addition, the benchmark is always started the moment the framework is invoked, and ended by the output class right before sending the final view to the browser, enabling a very accurate timing of the entire system execution to be shown.

Table of Contents • Benchmarking Class – Using the Benchmark Class – Profiling Your Benchmark Points – Displaying Total Execution Time – Displaying Memory Consumption

Using the Benchmark Class

The Benchmark class can be used within your controllers, views, or your models. The process for usage is this: 1. Mark a start point 2. Mark an end point 3. Run the “elapsed time” function to view the results Here’s an example using real code: $this->benchmark->mark(’code_start’);

// Some code happens here

$this->benchmark->mark(’code_end’);

69 CodeIgniter Documentation, 3.0-dev

echo $this->benchmark->elapsed_time(’code_start’, ’code_end’);

: The words “code_start” and “code_end” are arbitrary. They are simply words used to set two markers. You can use any words you want, and you can set multiple sets of markers. Consider this example: $this->benchmark->mark(’dog’);

// Some code happens here

$this->benchmark->mark(’cat’);

// More code happens here

$this->benchmark->mark(’bird’); echo $this->benchmark->elapsed_time(’dog’, ’cat’); echo $this->benchmark->elapsed_time(’cat’, ’bird’); echo $this->benchmark->elapsed_time(’dog’, ’bird’);

Profiling Your Benchmark Points

If you want your benchmark data to be available to the Profiler all of your marked points must be set up in pairs, and each mark point name must end with _start and _end. Each pair of points must otherwise be named identically. Example: $this->benchmark->mark(’my_mark_start’);

// Some code happens here...

$this->benchmark->mark(’my_mark_end’);

$this->benchmark->mark(’another_mark_start’);

// Some more code happens here...

$this->benchmark->mark(’another_mark_end’);

Please read the Profiler page for more information.

Displaying Total Execution Time

If you would like to display the total elapsed time from the moment CodeIgniter starts to the moment the final output is sent to the browser, simply place this in one of your view templates: benchmark->elapsed_time();?>

You’ll notice that it’s the same function used in the examples above to calculate the time between two point, except you are not using any parameters. When the parameters are absent, CodeIgniter does not stop the benchmark until right before the final output is sent to the browser. It doesn’t matter where you use the function call, the timer will continue to run until the very end. An alternate way to show your elapsed time in your view files is to use this pseudo-variable, if you prefer not to use the pure PHP:

70 Chapter 7. CodeIgniter Documentation, 3.0-dev

{elapsed_time}

: If you want to benchmark anything within your controller functions you must set your own start/end points.

Displaying Memory Consumption

If your PHP installation is configured with –enable-memory-limit, you can display the amount of memory consumed by the entire system using the following code in one of your view file: benchmark->memory_usage();?>

: This function can only be used in your view files. The consumption will reflect the total memory used by the entire app.

An alternate way to show your memory usage in your view files is to use this pseudo-variable, if you prefer not to use the pure PHP: {memory_usage}

7.1.2 Caching Driver

CodeIgniter features wrappers around some of the most popular forms of fast and dynamic caching. All but file-based caching require specific server requirements, and a Fatal Exception will be thrown if server requirements are not met.

Table of Contents • Caching Driver – Example Usage – Function Reference * is_supported() * get() * save() * delete() * clean() * cache_info() * get_metadata() – Drivers * Alternative PHP Cache (APC) Caching * File-based Caching * Memcached Caching * WinCache Caching * Redis Caching * Dummy Cache

Example Usage

The following example will load the cache driver, specify APC as the driver to use, and fall back to file-based caching if APC is not available in the hosting environment.

7.1. Libraries 71 CodeIgniter Documentation, 3.0-dev

$this->load->driver(’cache’, array(’adapter’ => ’apc’, ’backup’ => ’file’)); if ( ! $foo = $this->cache->get(’foo’)) { echo ’Saving to the cache!
’; $foo = ’foobarbaz!’;

// Save into the cache for 5 minutes $this->cache->save(’foo’, $foo, 300); } echo $foo;

You can also prefix cache item names via the key_prefix setting, which is useful to avoid collisions when you’re running multiple applications on the same environment. $this->load->driver(’cache’, array(’adapter’ => ’apc’, ’backup’ => ’file’, ’key_prefix’ => ’my_’) );

$this->cache->get(’foo’); // Will get the cache entry named ’my_foo’

Function Reference class CI_Cache is_supported()

CI_Cache::is_supported($driver) This function is automatically called when accessing drivers via $this->cache->get(). However, if the individual drivers are used, make sure to call this function to ensure the driver is supported in the hosting environment.

• $driver (string) – the name of the caching driver TRUE if supported, FALSE if not Boolean if ($this->cache->apc->is_supported() { if ($data = $this->cache->apc->get(’my_cache’)) { // do things. } }

get()

CI_Cache::get($id) This function will attempt to fetch an item from the cache store. If the item does not exist, the function will return FALSE.

72 Chapter 7. CodeIgniter Documentation, 3.0-dev

• $id (string) – name of cached item The item if it exists, FALSE if it does not Mixed $foo = $this->cache->get(’my_cached_item’);

save()

CI_Cache::save($id, $data[, $ttl ]) This function will save an item to the cache store. If saving fails, the function will return FALSE.

• $id (string) – name of the cached item • $data (mixed) – the data to save • $ttl (int) – Time To Live, in seconds (default 60) TRUE on success, FALSE on failure Boolean $this->cache->save(’cache_item_id’, ’data_to_cache’);

delete()

CI_Cache::delete($id) This function will delete a specific item from the cache store. If item deletion fails, the function will return FALSE.

• $id (string) – name of cached item TRUE if deleted, FALSE if the deletion fails Boolean $this->cache->delete(’cache_item_id’);

clean()

CI_Cache::clean() This function will ‘clean’ the entire cache. If the deletion of the cache files fails, the function will return FALSE. TRUE if deleted, FALSE if the deletion fails Boolean $this->cache->clean();

7.1. Libraries 73 CodeIgniter Documentation, 3.0-dev

cache_info()

CI_Cache::cache_info() This function will return information on the entire cache. information on the entire cache Mixed var_dump($this->cache->cache_info());

: The information returned and the structure of the data is dependent on which adapter is being used.

get_metadata()

CI_Cache::get_metadata($id) This function will return detailed information on a specific item in the cache.

• $id (string) – name of cached item metadadta for the cached item Mixed var_dump($this->cache->get_metadata(’my_cached_item’));

: The information returned and the structure of the data is dependent on which adapter is being used.

Drivers

Alternative PHP Cache (APC) Caching

All of the functions listed above can be accessed without passing a specific adapter to the driver loader as follows: $this->load->driver(’cache’); $this->cache->apc->save(’foo’, ’bar’, 10);

For more information on APC, please see http://php.net/apc.

File-based Caching

Unlike caching from the Output Class, the driver file-based caching allows for pieces of view files to be cached. Use this with care, and make sure to benchmark your application, as a point can come where disk I/O will negate positive gains by caching. All of the functions listed above can be accessed without passing a specific adapter to the driver loader as follows: $this->load->driver(’cache’); $this->cache->file->save(’foo’, ’bar’, 10);

74 Chapter 7. CodeIgniter Documentation, 3.0-dev

Memcached Caching

Multiple Memcached servers can be specified in the memcached.php configuration file, located in the _applica- tion/config/* directory. All of the methods listed above can be accessed without passing a specific adapter to the driver loader as follows: $this->load->driver(’cache’); $this->cache->memcached->save(’foo’, ’bar’, 10);

For more information on Memcached, please see http://php.net/memcached.

WinCache Caching

Under Windows, you can also utilize the WinCache driver. All of the functions listed above can be accessed without passing a specific adapter to the driver loader as follows: $this->load->driver(’cache’); $this->cache->wincache->save(’foo’, ’bar’, 10);

For more information on WinCache, please see http://php.net/wincache.

Redis Caching

Redis is an in-memory key-value store which can operate in LRU cache mode. To use it, you need Redis server and phpredis PHP extension https://github.com/nicolasff/phpredis. Config options to connect to redis server must be stored in the application/config/redis.php file. Available options are: $config[’socket_type’] = ’tcp’; //‘tcp‘ or ‘unix‘ $config[’socket’] = ’/var/run/redis.sock’; // in case of ‘unix‘ socket type $config[’host’] = ’127.0.0.1’; $config[’password’] = NULL; $config[’port’] = 6379; $config[’timeout’] = 0;

All of the methods listed above can be accessed without passing a specific adapter to the driver loader as follows: $this->load->driver(’cache’); $this->cache->redis->save(’foo’, ’bar’, 10);

For more information on Redis, please see http://redis.io.

Dummy Cache

This is a caching backend that will always ‘miss.’ It stores no data, but lets you keep your caching code in place in environments that don’t support your chosen cache.

7.1.3 Calendaring Class

The Calendar class enables you to dynamically create calendars. Your calendars can be formatted through the use of a calendar template, allowing 100% control over every aspect of its design. In addition, you can pass data to your calendar cells.

7.1. Libraries 75 CodeIgniter Documentation, 3.0-dev

Initializing the Class

Like most other classes in CodeIgniter, the Calendar class is initialized in your controller using the $this->load->library function: $this->load->library(’calendar’);

Once loaded, the Calendar object will be available using: $this->calendar

Displaying a Calendar

Here is a very simple example showing how you can display a calendar: $this->load->library(’calendar’); echo $this->calendar->generate();

The above code will generate a calendar for the current month/year based on your server time. To show a calendar for a specific month and year you will pass this information to the calendar generating function: $this->load->library(’calendar’); echo $this->calendar->generate(2006, 6);

The above code will generate a calendar showing the month of June in 2006. The first parameter specifies the year, the second parameter specifies the month.

Passing Data to your Calendar Cells

To add data to your calendar cells involves creating an associative array in which the keys correspond to the days you wish to populate and the array value contains the data. The array is passed to the third parameter of the calendar generating function. Consider this example: $this->load->library(’calendar’);

$data = array( 3 => ’http://example.com/news/article/2006/03/’, 7 => ’http://example.com/news/article/2006/07/’, 13 => ’http://example.com/news/article/2006/13/’, 26 => ’http://example.com/news/article/2006/26/’ ); echo $this->calendar->generate(2006, 6, $data);

Using the above example, day numbers 3, 7, 13, and 26 will become links pointing to the URLs you’ve provided.

: By default it is assumed that your array will contain links. In the section that explains the calendar template below you’ll see how you can customize how data passed to your cells is handled so you can pass different types of information.

Setting Display Preferences

There are seven preferences you can set to control various aspects of the calendar. Preferences are set by passing an array of preferences in the second parameter of the loading function. Here is an example:

76 Chapter 7. CodeIgniter Documentation, 3.0-dev

$prefs = array ( ’start_day’ => ’saturday’, ’month_type’ => ’long’, ’day_type’ => ’short’ );

$this->load->library(’calendar’, $prefs); echo $this->calendar->generate();

The above code would start the calendar on saturday, use the “long” month heading, and the “short” day names. More information regarding preferences below. Prefer- De- Options Description ence fault template None None A string containing your calendar template. See the template section below. lo- time() None A Unix timestamp corresponding to the current time. cal_time start_day sun- Any week day (sunday, Sets the day of the week the calendar should start on. day monday, tuesday, etc.) month_typelong long, short Determines what version of the month name to use in the header. long = January, short = Jan. day_type abr long, short, abr Determines what version of the weekday names to use in the column headers. long = Sunday, short = Sun, abr = Su. show_next_prevFALSETRUE/FALSE (boolean) Determines whether to display links allowing you to toggle to next/previous months. See information on this feature below. next_prev_urlNone A URL Sets the basepath used in the next/previous calendar links.

Showing Next/Previous Month Links

To allow your calendar to dynamically increment/decrement via the next/previous links requires that you set up your calendar code similar to this example: $prefs = array ( ’show_next_prev’ => TRUE, ’next_prev_url’ => ’http://example.com/index.php/calendar/show/’ );

$this->load->library(’calendar’, $prefs); echo $this->calendar->generate($this->uri->segment(3), $this->uri->segment(4));

You’ll notice a few things about the above example: • You must set the “show_next_prev” to TRUE. • You must supply the URL to the controller containing your calendar in the “next_prev_url” preference. • You must supply the “year” and “month” to the calendar generating function via the URI segments where they appear (Note: The calendar class automatically adds the year/month to the base URL you provide.).

Creating a Calendar Template

By creating a calendar template you have 100% control over the design of your calendar. Each component of your calendar will be placed within a pair of pseudo-variables as shown here:

7.1. Libraries 77 CodeIgniter Documentation, 3.0-dev

$prefs[’template’] = ’

{table_open}

{/table_open}

{heading_row_start}

{/heading_row_start}

{heading_previous_cell}

{/heading_previous_cell} {heading_title_cell}{/heading_title_cell} {heading_next_cell}{/heading_next_cell}

{heading_row_end}

{/heading_row_end}

{week_row_start}

{/week_row_start} {week_day_cell}{/week_day_cell} {week_row_end}{/week_row_end}

{cal_row_start}

{/cal_row_start} {cal_cell_start}{/cal_cell_end} {cal_row_end}{/cal_row_end}

{table_close}

<<{heading}>>
{week_day}
{/cal_cell_start}

{cal_cell_content}{day}{/cal_cell_content} {cal_cell_content_today}

{/cal_cell_content_today}

{cal_cell_no_content}{day}{/cal_cell_no_content} {cal_cell_no_content_today}

{day}
{/cal_cell_no_content_today}

{cal_cell_blank} {/cal_cell_blank}

{cal_cell_end}

{/table_close} ’;

$this->load->library(’calendar’, $prefs); echo $this->calendar->generate();

7.1.4 Shopping Cart Class

The Cart Class permits items to be added to a session that stays active while a user is browsing your site. These items can be retrieved and displayed in a standard “shopping cart” format, allowing the user to update the quantity or remove items from the cart. Please note that the Cart Class ONLY provides the core “cart” functionality. It does not provide shipping, credit card authorization, or other processing components.

78 Chapter 7. CodeIgniter Documentation, 3.0-dev

Page Contents • Shopping Cart Class – Initializing the Shopping Cart Class – Adding an Item to The Cart – Adding Multiple Items to The Cart – Displaying the Cart – Updating The Cart * What is a Row ID? – Function Reference * $this->cart->insert(); * $this->cart->update(); * $this->cart->remove(rowid); * $this->cart->total(); * $this->cart->total_items(); * $this->cart->contents(boolean); * $this->cart->get_item($row_id); * $this->cart->has_options($row_id); * $this->cart->product_options($row_id); * $this->cart->destroy();

Initializing the Shopping Cart Class

: The Cart class utilizes CodeIgniter’s Session Class to save the cart information to a database, so before using the Cart class you must set up a database table as indicated in the Session Documentation, and set the session preferences in your application/config/config.php file to utilize a database.

To initialize the Shopping Cart Class in your controller constructor, use the $this->load->library function: $this->load->library(’cart’);

Once loaded, the Cart object will be available using: $this->cart

: The Cart Class will load and initialize the Session Class automatically, so unless you are using sessions elsewhere in your application, you do not need to load the Session class.

Adding an Item to The Cart

To add an item to the shopping cart, simply pass an array with the product information to the $this->cart->insert() function, as shown below: $data = array( ’id’ => ’sku_123ABC’, ’qty’ => 1, ’price’ => 39.95, ’name’ => ’T-Shirt’, ’options’ => array(’Size’ => ’L’, ’Color’ => ’Red’) );

$this->cart->insert($data);

7.1. Libraries 79 CodeIgniter Documentation, 3.0-dev

: The first four array indexes above (id, qty, price, and name) are required. If you omit any of them the data will not be saved to the cart. The fifth index (options) is optional. It is intended to be used in cases where your product has options associated with it. Use an array for options, as shown above.

The five reserved indexes are: • id - Each product in your store must have a unique identifier. Typically this will be an “sku” or other such identifier. • qty - The quantity being purchased. • price - The price of the item. • name - The name of the item. • options - Any additional attributes that are needed to identify the product. These must be passed via an array. In addition to the five indexes above, there are two reserved words: rowid and subtotal. These are used internally by the Cart class, so please do NOT use those words as index names when inserting data into the cart. Your array may contain additional data. Anything you include in your array will be stored in the session. However, it is best to standardize your data among all your products in order to make displaying the information in a table easier. The insert() method will return the $rowid if you successfully insert a single item.

Adding Multiple Items to The Cart

By using a multi-dimensional array, as shown below, it is possible to add multiple products to the cart in one action. This is useful in cases where you wish to allow people to select from among several items on the same page. $data = array( array( ’id’ => ’sku_123ABC’, ’qty’ => 1, ’price’ => 39.95, ’name’ => ’T-Shirt’, ’options’ => array(’Size’ => ’L’, ’Color’ => ’Red’) ), array( ’id’ => ’sku_567ZYX’, ’qty’ => 1, ’price’ => 9.95, ’name’ => ’Coffee Mug’ ), array( ’id’ => ’sku_965QRS’, ’qty’ => 1, ’price’ => 29.95, ’name’ => ’Shot Glass’ ) );

$this->cart->insert($data);

Displaying the Cart

To display the cart you will create a view file with code similar to the one shown below.

80 Chapter 7. CodeIgniter Documentation, 3.0-dev

Please note that this example uses the form helper.

cart->contents() as $items): ?>

QTY Item Description Item Price Sub-Total
$i.’[qty]’, ’value’ => $items[’qty’], ’maxlength’ => ’3’, ’size’ => ’5’)); ?>

cart->has_options($items[’rowid’]) == TRUE): ?>

cart->product_options($items[’rowid’]) as $option_name => $option_value): ?>

:

cart->format_number($items[’price’]); ?> $cart->format_number($items[’subtotal’]); ?>
Total $cart->format_number($this->cart->total()); ?>

7.1. Libraries 81 CodeIgniter Documentation, 3.0-dev

Updating The Cart

To update the information in your cart, you must pass an array containing the Row ID and quantity to the $this->cart- >update() function:

: If the quantity is set to zero, the item will be removed from the cart.

$data = array( ’rowid’ => ’b99ccdf16028f015540f341130b6d8ec’, ’qty’ => 3 );

$this->cart->update($data);

// Or a multi-dimensional array

$data = array( array( ’rowid’ => ’b99ccdf16028f015540f341130b6d8ec’, ’qty’ => 3 ), array( ’rowid’ => ’xw82g9q3r495893iajdh473990rikw23’, ’qty’ => 4 ), array( ’rowid’ => ’fh4kdkkkaoe30njgoe92rkdkkobec333’, ’qty’ => 2 ) );

$this->cart->update($data);

What is a Row ID?

The row ID is a unique identifier that is generated by the cart code when an item is added to the cart. The reason a unique ID is created is so that identical products with different options can be managed by the cart. For example, let’s say someone buys two identical t-shirts (same product ID), but in different sizes. The product ID (and other attributes) will be identical for both sizes because it’s the same shirt. The only difference will be the size. The cart must therefore have a means of identifying this difference so that the two sizes of shirts can be managed independently. It does so by creating a unique “row ID” based on the product ID and any options associated with it. In nearly all cases, updating the cart will be something the user does via the “view cart” page, so as a developer, it is unlikely that you will ever have to concern yourself with the “row ID”, other then making sure your “view cart” page contains this information in a hidden form field, and making sure it gets passed to the update function when the update form is submitted. Please examine the construction of the “view cart” page above for more information.

Function Reference

$this->cart->insert();

Permits you to add items to the shopping cart, as outlined above.

82 Chapter 7. CodeIgniter Documentation, 3.0-dev

$this->cart->update();

Permits you to update items in the shopping cart, as outlined above.

$this->cart->remove(rowid);

Allows you to remove an item from the shopping cart by passing it the rowid.

$this->cart->total();

Displays the total amount in the cart.

$this->cart->total_items();

Displays the total number of items in the cart.

$this->cart->contents(boolean);

Returns an array containing everything in the cart. You can sort the order, by which this is returned by passing it “true” where the contents will be sorted from newest to oldest, by leaving this function blank, you’ll automatically just get first added to the basket to last added to the basket.

$this->cart->get_item($row_id);

Returns an array containing data for the item matching the specified row ID, or FALSE if no such item exists.

$this->cart->has_options($row_id);

Returns TRUE (boolean) if a particular row in the cart contains options. This function is designed to be used in a loop with $this->cart->contents(), since you must pass the rowid to this function, as shown in the Displaying the Cart example above.

$this->cart->product_options($row_id);

Returns an array of options for a particular product. This function is designed to be used in a loop with $this->cart- >contents(), since you must pass the rowid to this function, as shown in the Displaying the Cart example above.

$this->cart->destroy();

Permits you to destroy the cart. This function will likely be called when you are finished processing the customer’s order.

7.1. Libraries 83 CodeIgniter Documentation, 3.0-dev

7.1.5 Config Class

The Config class provides a means to retrieve configuration preferences. These preferences can come from the default config file (application/config/config.php) or from your own custom config files.

: This class is initialized automatically by the system so there is no need to do it manually.

Page Contents • Config Class – Anatomy of a Config File – Loading a Config File * Manual Loading * Auto-loading – Fetching Config Items – Setting a Config Item – Environments – Helper Functions * $this->config->site_url(); * $this->config->base_url(); * $this->config->system_url();

Anatomy of a Config File

By default, CodeIgniter has one primary config file, located at application/config/config.php. If you open the file using your text editor you’ll see that config items are stored in an array called $config. You can add your own config items to this file, or if you prefer to keep your configuration items separate (assuming you even need config items), simply create your own file and save it in config folder.

: If you do create your own config files use the same format as the primary one, storing your items in an array called $config. CodeIgniter will intelligently manage these files so there will be no conflict even though the array has the same name (assuming an array index is not named the same as another).

Loading a Config File

: CodeIgniter automatically loads the primary config file (application/config/config.php), so you will only need to load a config file if you have created your own.

There are two ways to load a config file:

Manual Loading

To load one of your custom config files you will use the following function within the controller that needs it: $this->config->load(’filename’);

Where filename is the name of your config file, without the .php file extension.

84 Chapter 7. CodeIgniter Documentation, 3.0-dev

If you need to load multiple config files normally they will be merged into one master config array. Name collisions can occur, however, if you have identically named array indexes in different config files. To avoid collisions you can set the second parameter to TRUE and each config file will be stored in an array index corresponding to the name of the config file. Example: // Stored in an array with this prototype: $this->config[’blog_settings’] = $config $this->config->load(’blog_settings’, TRUE);

Please see the section entitled Fetching Config Items below to learn how to retrieve config items set this way. The third parameter allows you to suppress errors in the event that a config file does not exist: $this->config->load(’blog_settings’, FALSE, TRUE);

Auto-loading

If you find that you need a particular config file globally, you can have it loaded automatically by the system. To do this, open the autoload.php file, located at application/config/autoload.php, and add your config file as indicated in the file.

Fetching Config Items

To retrieve an item from your config file, use the following function: $this->config->item(’item name’);

Where item name is the $config array index you want to retrieve. For example, to fetch your language choice you’ll do this: $lang = $this->config->item(’language’);

The function returns NULL if the item you are trying to fetch does not exist. If you are using the second parameter of the $this->config->load function in order to assign your config items to a specific index you can retrieve it by specifying the index name in the second parameter of the $this->config->item() function. Example: // Loads a config file named blog_settings.php and assigns it to an index named "blog_settings" $this->config->load(’blog_settings’, TRUE);

// Retrieve a config item named site_name contained within the blog_settings array $site_name = $this->config->item(’site_name’, ’blog_settings’);

// An alternate way to specify the same item: $blog_config = $this->config->item(’blog_settings’); $site_name = $blog_config[’site_name’];

Setting a Config Item

If you would like to dynamically set a config item or change an existing one, you can do so using: $this->config->set_item(’item_name’, ’item_value’);

Where item_name is the $config array index you want to change, and item_value is its value.

7.1. Libraries 85 CodeIgniter Documentation, 3.0-dev

Environments

You may load different configuration files depending on the current environment. The ENVIRONMENT constant is defined in index.php, and is described in detail in the Handling Environments section. To create an environment-specific configuration file, create or copy a configuration file in applica- tion/config/{ENVIRONMENT}/{FILENAME}.php For example, to create a production-only config.php, you would: 1. Create the directory application/config/production/ 2. Copy your existing config.php into the above directory 3. Edit application/config/production/config.php so it contains your production settings When you set the ENVIRONMENT constant to ‘production’, the settings for your new production-only config.php will be loaded. You can place the following configuration files in environment-specific folders: • Default CodeIgniter configuration files • Your own custom configuration files

: CodeIgniter always loads the global config file first (i.e., the one in application/config/), then tries to load the configuration files for the current environment. This means you are not obligated to place all of your configuration files in an environment folder. Only the files that change per environment. Additionally you don’t have to copy all the config items in the environment config file. Only the config items that you wish to change for your environment. The config items declared in your environment folders always overwrite those in your global config files.

Helper Functions

The config class has the following helper functions:

$this->config->site_url();

This function retrieves the URL to your site, along with the “index” value you’ve specified in the config file.

$this->config->base_url();

This function retrieves the URL to your site, plus an optional path such as to a stylesheet or image. The two functions above are normally accessed via the corresponding functions in the URL Helper.

$this->config->system_url();

This function retrieves the URL to your system folder.

7.1.6 Email Class

CodeIgniter’s robust Email Class supports the following features: • Multiple Protocols: Mail, Sendmail, and SMTP

86 Chapter 7. CodeIgniter Documentation, 3.0-dev

• TLS and SSL Encryption for SMTP • Multiple recipients • CC and BCCs • HTML or Plaintext email • Attachments • Word wrapping • Priorities • BCC Batch Mode, enabling large email lists to be broken into small BCC batches. • Email Debugging tools

Sending Email

Sending email is not only simple, but you can configure it on the fly or set your preferences in a config file. Here is a basic example demonstrating how you might send email. Note: This example assumes you are sending the email from one of your controllers. $this->load->library(’email’);

$this->email->from(’[email protected]’, ’Your Name’); $this->email->to(’[email protected]’); $this->email->cc(’[email protected]’); $this->email->bcc(’[email protected]’);

$this->email->subject(’Email Test’); $this->email->message(’Testing the email class.’);

$this->email->send();

Setting Email Preferences

There are 21 different preferences available to tailor how your email messages are sent. You can either set them manually as described here, or automatically via preferences stored in your config file, described below: Preferences are set by passing an array of preference values to the email initialize method. Here is an example of how you might set some preferences: $config[’protocol’] = ’sendmail’; $config[’mailpath’] = ’/usr/sbin/sendmail’; $config[’charset’] = ’iso-8859-1’; $config[’wordwrap’] = TRUE;

$this->email->initialize($config);

: Most of the preferences have default values that will be used if you do not set them.

Setting Email Preferences in a Config File

If you prefer not to set preferences using the above method, you can instead put them into a config file. Simply create a new file called the email.php, add the $config array in that file. Then save the file at config/email.php and it will

7.1. Libraries 87 CodeIgniter Documentation, 3.0-dev be used automatically. You will NOT need to use the $this->email->initialize() method if you save your preferences in a config file.

Email Preferences

The following is a list of all the preferences that can be set when sending email. Prefer- Default Options Description ence Value usera- CodeIgniter None The “user agent”. gent proto- mail mail, The mail sending protocol. col sendmail, or smtp mail- /usr/sbin/sendmailNone The server path to Sendmail. path smtp_hostNo Default None SMTP Server Address. smtp_userNo Default None SMTP Username. smtp_passNo Default None SMTP Password. smtp_port25 None SMTP Port. smtp_timeout5 None SMTP Timeout (in seconds). smtp_keepaliveFALSE TRUE or Enable persistent SMTP connections. FALSE (boolean) smtp_cryptoNo Default tls or ssl SMTP Encryption word- TRUE TRUE or Enable word-wrap. wrap FALSE (boolean) wrapchars76 Character count to wrap at. mailtype text text or html Type of mail. If you send HTML email you must send it as a complete web page. Make sure you don’t have any relative links or relative image paths otherwise they will not work. charset $config[’charset’] Character set (utf-8, iso-8859-1, etc.). vali- FALSE TRUE or Whether to validate the email address. date FALSE (boolean) prior- 3 1, 2, 3, 4, 5 Email Priority. 1 = highest. 5 = lowest. 3 = normal. ity crlf \n “\r\n” or Newline character. (Use “\r\n” to comply with RFC 822). “\n” or “\r” new- \n “\r\n” or Newline character. (Use “\r\n” to comply with RFC 822). line “\n” or “\r” bcc_batch_modeFALSE TRUE or Enable BCC Batch Mode. FALSE (boolean) bcc_batch_size200 None Number of emails in each BCC batch. dsn FALSE TRUE or Enable notify message from server FALSE (boolean)

88 Chapter 7. CodeIgniter Documentation, 3.0-dev

Email Methods Reference

$this->email->from()

Sets the email address and name of the person sending the email: $this->email->from(’[email protected]’, ’Your Name’);

You can also set a Return-Path, to help redirect undelivered mail: $this->email->from(’[email protected]’, ’Your Name’, ’[email protected]’);

: Return-Path can’t be used if you’ve configured ‘smtp’ as your protocol.

$this->email->reply_to()

Sets the reply-to address. If the information is not provided the information in the “from” method is used. Example: $this->email->reply_to(’[email protected]’, ’Your Name’);

$this->email->to()

Sets the email address(s) of the recipient(s). Can be a single email, a comma-delimited list or an array: $this->email->to(’[email protected]’);

$this->email->to(’[email protected], [email protected], [email protected]’);

$list = array(’[email protected]’, ’[email protected]’, ’[email protected]’);

$this->email->to($list);

$this->email->cc()

Sets the CC email address(s). Just like the “to”, can be a single email, a comma-delimited list or an array.

$this->email->bcc()

Sets the BCC email address(s). Just like the “to”, can be a single email, a comma-delimited list or an array.

$this->email->subject()

Sets the email subject: $this->email->subject(’This is my subject’);

7.1. Libraries 89 CodeIgniter Documentation, 3.0-dev

$this->email->message()

Sets the email message body: $this->email->message(’This is my message’);

$this->email->set_alt_message()

Sets the alternative email message body: $this->email->set_alt_message(’This is the alternative message’);

This is an optional message string which can be used if you send HTML formatted email. It lets you specify an alternative message with no HTML formatting which is added to the header string for people who do not accept HTML email. If you do not set your own message CodeIgniter will extract the message from your HTML email and strip the tags.

$this->email->set_header()

Appends additional headers to the e-mail: $this->email->set_header(’Header1’, ’Value1’); $this->email->set_header(’Header2’, ’Value2’);

$this->email->clear()

Initializes all the email variables to an empty state. This method is intended for use if you run the email sending method in a loop, permitting the data to be reset between cycles. foreach ($list as $name => $address) { $this->email->clear();

$this->email->to($address); $this->email->from(’[email protected]’); $this->email->subject(’Here is your info ’.$name); $this->email->message(’Hi ’.$name.’ Here is the info you requested.’); $this->email->send(); }

If you set the parameter to TRUE any attachments will be cleared as well: $this->email->clear(TRUE);

$this->email->send()

The Email sending method. Returns boolean TRUE or FALSE based on success or failure, enabling it to be used conditionally: if ( ! $this->email->send()) { // Generate error }

90 Chapter 7. CodeIgniter Documentation, 3.0-dev

This method will automatically clear all parameters if the request was successful. To stop this behaviour pass FALSE: if ($this->email->send(FALSE)) { // Parameters won’t be cleared }

: In order to use the print_debugger() method, you need to avoid clearing the email parameters.

$this->email->attach()

Enables you to send an attachment. Put the file path/name in the first parameter. Note: Use a file path, not a URL. For multiple attachments use the method multiple times. For example: $this->email->attach(’/path/to/photo1.jpg’); $this->email->attach(’/path/to/photo2.jpg’); $this->email->attach(’/path/to/photo3.jpg’);

To use the default disposition (attachment), leave the second parameter blank, otherwise use a custom disposition: $this->email->attach(’image.jpg’, ’inline’);

If you’d like to use a custom file name, you can use the third paramater: $this->email->attach(’filename.pdf’, ’attachment’, ’report.pdf’);

If you need to use a buffer string instead of a real - physical - file you can use the first parameter as buffer, the third parameter as file name and the fourth parameter as mime-type: $this->email->attach($buffer, ’attachment’, ’report.pdf’, ’application/pdf’);

$this->email->print_debugger()

Returns a string containing any server messages, the email headers, and the email messsage. Useful for debugging. You can optionally specify which parts of the message should be printed. Valid options are: headers, subject, body. Example: // You need to pass FALSE while sending in order for the email data // to not be cleared - if that happens, print_debugger() would have // nothing to output. $this->email->send(FALSE);

// Will only print the email headers, excluding the message subject and body $this->email->print_debugger(array(’headers’));

: By default, all of the raw data will be printed.

Overriding Word Wrapping

If you have word wrapping enabled (recommended to comply with RFC 822) and you have a very long link in your email it can get wrapped too, causing it to become un-clickable by the person receiving it. CodeIgniter lets you manually override word wrapping within part of your message like this:

7.1. Libraries 91 CodeIgniter Documentation, 3.0-dev

The text of your email that gets wrapped normally.

{unwrap}http://example.com/a_long_link_that_should_not_be_wrapped.html{/unwrap}

More text that will be wrapped normally.

Place the item you do not want word-wrapped between: {unwrap} {/unwrap}

7.1.7 Encryption Class

The Encryption Class provides two-way data encryption. It uses a scheme that either compiles the message using a randomly hashed bitwise XOR encoding scheme, or is encrypted using the Mcrypt library. If Mcrypt is not available on your server the encoded message will still provide a reasonable degree of security for encrypted sessions or other such “light” purposes. If Mcrypt is available, you’ll be provided with a high degree of security appropriate for storage.

Setting your Key

A key is a piece of information that controls the cryptographic process and permits an encrypted string to be decoded. In fact, the key you chose will provide the only means to decode data that was encrypted with that key, so not only must you choose the key carefully, you must never change it if you intend use it for persistent data. It goes without saying that you should guard your key carefully. Should someone gain access to your key, the data will be easily decoded. If your server is not totally under your control it’s impossible to ensure key security so you may want to think carefully before using it for anything that requires high security, like storing credit card numbers. To take maximum advantage of the encryption algorithm, your key should be 32 characters in length (256 bits). The key should be as random a string as you can concoct, with numbers and uppercase and lowercase letters. Your key should not be a simple text string. In order to be cryptographically secure it needs to be as random as possible. Your key can be either stored in your application/config/config.php, or you can design your own storage mechanism and pass the key dynamically when encoding/decoding. To save your key to your application/config/config.php, open the file and set: $config[’encryption_key’] = "YOUR KEY";

Message Length

It’s important for you to know that the encoded messages the encryption function generates will be approximately 2.6 times longer than the original message. For example, if you encrypt the string “my super secret data”, which is 21 characters in length, you’ll end up with an encoded string that is roughly 55 characters (we say “roughly” because the encoded string length increments in 64 bit clusters, so it’s not exactly linear). Keep this information in mind when selecting your data storage mechanism. Cookies, for example, can only hold 4K of information.

Initializing the Class

Like most other classes in CodeIgniter, the Encryption class is initialized in your controller using the $this->load- >library function: $this->load->library(’encrypt’);

Once loaded, the Encrypt library object will be available using: $this->encrypt

92 Chapter 7. CodeIgniter Documentation, 3.0-dev

$this->encrypt->encode()

Performs the data encryption and returns it as a string. Example: $msg = ’My secret message’;

$encrypted_string = $this->encrypt->encode($msg);

You can optionally pass your encryption key via the second parameter if you don’t want to use the one in your config file: $msg = ’My secret message’; $key = ’super-secret-key’;

$encrypted_string = $this->encrypt->encode($msg, $key);

$this->encrypt->decode()

Decrypts an encoded string. Example: $encrypted_string = ’APANtByIGI1BpVXZTJgcsAG8GZl8pdwwa84’;

$plaintext_string = $this->encrypt->decode($encrypted_string);

You can optionally pass your encryption key via the second parameter if you don’t want to use the one in your config file: $msg = ’My secret message’; $key = ’super-secret-key’;

$encrypted_string = $this->encrypt->decode($msg, $key);

$this->encrypt->set_cipher();

Permits you to set an Mcrypt cipher. By default it uses MCRYPT_RIJNDAEL_256. Example: $this->encrypt->set_cipher(MCRYPT_BLOWFISH);

Please visit php.net for a list of available ciphers. If you’d like to manually test whether your server supports Mcrypt you can use: echo ( ! function_exists(’mcrypt_encrypt’)) ? ’Nope’ : ’Yup’;

$this->encrypt->set_mode();

Permits you to set an Mcrypt mode. By default it uses MCRYPT_MODE_CBC. Example: $this->encrypt->set_mode(MCRYPT_MODE_CFB);

Please visit php.net for a list of available modes.

7.1. Libraries 93 CodeIgniter Documentation, 3.0-dev

$this->encrypt->encode_from_legacy($orig_data, $legacy_mode = MCRYPT_MODE_ECB, $key = ‘’);

Enables you to re-encode data that was originally encrypted with CodeIgniter 1.x to be compatible with the Encryption library in CodeIgniter 2.x. It is only necessary to use this method if you have encrypted data stored permanently such as in a file or database and are on a server that supports Mcrypt. “Light” use encryption such as encrypted session data or transitory encrypted flashdata require no intervention on your part. However, existing encrypted Sessions will be destroyed since data encrypted prior to 2.x will not be decoded.

: Why only a method to re-encode the data instead of maintaining legacy methods for both encoding and decoding? The algorithms in the Encryption library have improved in CodeIgniter 2.x both for performance and security, and we do not wish to encourage continued use of the older methods. You can of course extend the Encryption library if you wish and replace the new methods with the old and retain seamless compatibility with CodeIgniter 1.x encrypted data, but this a decision that a developer should make cautiously and deliberately, if at all.

$new_data = $this->encrypt->encode_from_legacy($old_encrypted_string);

Pa- Default Description rame- ter $orig_datan/a The original encrypted data from CodeIgniter 1.x’s Encryption library $legacy_modeMCRYPT_MODE_ECBThe Mcrypt mode that was used to generate the original encrypted data. CodeIgniter 1.x’s default was MCRYPT_MODE_ECB, and it will assume that to be the case unless overridden by this parameter. $key n/a The encryption key. This it typically specified in your config file as outlined above.

7.1.8 File Uploading Class

CodeIgniter’s File Uploading Class permits files to be uploaded. You can set various preferences, restricting the type and size of the files.

The Process

Uploading a file involves the following general process: • An upload form is displayed, allowing a user to select a file and upload it. • When the form is submitted, the file is uploaded to the destination you specify. • Along the way, the file is validated to make sure it is allowed to be uploaded based on the preferences you set. • Once uploaded, the user will be shown a success message. To demonstrate this process here is brief tutorial. Afterward you’ll find reference information.

Creating the Upload Form

Using a text editor, create a form called upload_form.php. In it, place this code and save it to your application/views/ directory: Upload Form

94 Chapter 7. CodeIgniter Documentation, 3.0-dev



You’ll notice we are using a form helper to create the opening form tag. File uploads require a multipart form, so the helper creates the proper syntax for you. You’ll also notice we have an $error variable. This is so we can show error messages in the event the user does something wrong.

The Success Page

Using a text editor, create a form called upload_success.php. In it, place this code and save it to your applica- tion/views/ directory: Upload Form

Your file was successfully uploaded!

    $value):?>
  • :

The Controller

Using a text editor, create a controller called Upload.php. In it, place this code and save it to your applica- tion/controllers/ directory:

public function __construct() { parent::__construct();

7.1. Libraries 95 CodeIgniter Documentation, 3.0-dev

$this->load->helper(array(’form’, ’url’)); }

public function index() { $this->load->view(’upload_form’, array(’error’ => ’ ’ )); }

public function do_upload() { $config[’upload_path’] = ’./uploads/’; $config[’allowed_types’] = ’gif|jpg|png’; $config[’max_size’] = 100; $config[’max_width’] = 1024; $config[’max_height’] = 768;

$this->load->library(’upload’, $config);

if ( ! $this->upload->do_upload()) { $error = array(’error’ => $this->upload->display_errors());

$this->load->view(’upload_form’, $error); } else { $data = array(’upload_data’ => $this->upload->data());

$this->load->view(’upload_success’, $data); } } } ?>

The Upload Directory

You’ll need a destination directory for your uploaded images. Create a directory at the root of your CodeIgniter installation called uploads and set its file permissions to 777.

Try it!

To try your form, visit your site using a URL similar to this one: example.com/index.php/upload/

You should see an upload form. Try uploading an image file (either a jpg, gif, or png). If the path in your controller is correct it should work.

Reference Guide

Initializing the Upload Class

Like most other classes in CodeIgniter, the Upload class is initialized in your controller using the $this->load->library() method:

96 Chapter 7. CodeIgniter Documentation, 3.0-dev

$this->load->library(’upload’);

Once the Upload class is loaded, the object will be available using: $this->upload

Setting Preferences

Similar to other libraries, you’ll control what is allowed to be upload based on your preferences. In the controller you built above you set the following preferences: $config[’upload_path’] = ’./uploads/’; $config[’allowed_types’] = ’gif|jpg|png’; $config[’max_size’] = ’100’; $config[’max_width’] = ’1024’; $config[’max_height’] = ’768’;

$this->load->library(’upload’, $config);

// Alternately you can set preferences by calling the ‘‘initialize()‘‘ method. Useful if you auto-load the class: $this->upload->initialize($config);

The above preferences should be fairly self-explanatory. Below is a table describing all available preferences.

Preferences

The following preferences are available. The default value indicates what will be used if you do not specify that preference.

7.1. Libraries 97 CodeIgniter Documentation, 3.0-dev

Prefer- De- Options Description ence fault Value up- None None The path to the directory where the upload should be placed. The directory load_path must be writable and the path can be absolute or relative. al- None None The mime types corresponding to the types of files you allow to be lowed_types uploaded. Usually the file extension can be used as the mime type. Separate multiple types with a pipe. file_name None Desired If set CodeIgniter will rename the uploaded file to this name. The file name extension provided in the file name must also be an allowed file type. If no extension is provided in the original file_name will be used. file_ext_tolowerFALSE TRUE/FALSEIf set to TRUE, the file extension will be forced to lower case (boolean) overwrite FALSE TRUE/FALSEIf set to true, if a file with the same name as the one you are uploading (boolean) exists, it will be overwritten. If set to false, a number will be appended to the filename if another with the same name exists. max_size 0 None The maximum size (in kilobytes) that the file can be. Set to zero for no limit. Note: Most PHP installations have their own limit, as specified in the php.ini file. Usually 2 MB (or 2048 KB) by default. max_width 0 None The maximum width (in pixels) that the image can be. Set to zero for no limit. max_height 0 None The maximum height (in pixels) that the image can be. Set to zero for no limit. min_width 0 None The minimum width (in pixels) that the image can be. Set to zero for no limit. min_height 0 None The minimum height (in pixels) that the image can be. Set to zero for no limit. max_filename0 None The maximum length that a file name can be. Set to zero for no limit. max_filename_increment100 None When overwrite is set to FALSE, use this to set the maximum filename increment for CodeIgniter to append to the filename. en- FALSE TRUE/FALSEIf set to TRUE the file name will be converted to a random encrypted crypt_name (boolean) string. This can be useful if you would like the file saved with a name that can not be discerned by the person uploading it. re- TRUE TRUE/FALSEIf set to TRUE, any spaces in the file name will be converted to move_spaces (boolean) underscores. This is recommended. de- TRUE TRUE/FALSEIf set to TRUE, a server side detection of the file type will be performed to tect_mime (boolean) avoid code injection attacks. DO NOT disable this option unless you have no other option as that would cause a security risk. mod_mime_fixTRUE TRUE/FALSEIf set to TRUE, multiple filename extensions will be suffixed with an (boolean) underscore in order to avoid triggering Apache mod_mime. DO NOT turn off this option if your upload directory is public, as this is a security risk.

Setting preferences in a config file

If you prefer not to set preferences using the above method, you can instead put them into a config file. Simply create a new file called the upload.php, add the $config array in that file. Then save the file in: config/upload.php and it will be used automatically. You will NOT need to use the $this->upload->initialize() method if you save your preferences in a config file.

Class Reference

The following methods are available:

98 Chapter 7. CodeIgniter Documentation, 3.0-dev

$this->upload->do_upload()

Performs the upload based on the preferences you’ve set.

: By default the upload routine expects the file to come from a form field called userfile, and the form must be of type “multipart”.

If you would like to set your own field name simply pass its value to the do_upload() method: $field_name = "some_field_name"; $this->upload->do_upload($field_name);

$this->upload->display_errors()

Retrieves any error messages if the do_upload() method returned false. The method does not echo automatically, it returns the data so you can assign it however you need.

Formatting Errors By default the above method wraps any errors within

tags. You can set your own delimiters like this: $this->upload->display_errors(’

’, ’

’);

$this->upload->data()

This is a helper method that returns an array containing all of the data related to the file you uploaded. Here is the array prototype: Array ( [file_name] => mypic.jpg [file_type] => image/jpeg [file_path] => /path/to/your/upload/ [full_path] => /path/to/your/upload/jpg.jpg [raw_name] => mypic [orig_name] => mypic.jpg [client_name] => mypic.jpg [file_ext] => .jpg [file_size] => 22.2 [is_image] => 1 [image_width] => 800 [image_height] => 600 [image_type] => jpeg [image_size_str] => width="800" height="200" )

To return one element from the array: $this->upload->data(’file_name’); // Returns: mypic.jpg

7.1. Libraries 99 CodeIgniter Documentation, 3.0-dev

Explanation Here is an explanation of the above array items. Item Description file_name The name of the file that was uploaded including the file extension. file_type The file’s Mime type file_path The absolute server path to the file full_path The absolute server path including the file name raw_name The file name without the extension orig_name The original file name. This is only useful if you use the encrypted name option. client_name The file name as supplied by the client user agent, prior to any file name preparation or incrementing. file_ext The file extension with period file_size The file size in kilobytes is_image Whether the file is an image or not. 1 = image. 0 = not. image_width Image width. image_height Image height image_type Image type. Typically the file extension without the period. image_size_str A string containing the width and height. Useful to put into an image tag.

7.1.9 Form Validation

CodeIgniter provides a comprehensive form validation and data prepping class that helps minimize the amount of code you’ll write.

100 Chapter 7. CodeIgniter Documentation, 3.0-dev

Page Contents • Form Validation – Overview – Form Validation Tutorial * The Form * The Success Page * The Controller * Try it! * Explanation * Setting Validation Rules * Setting Rules Using an Array * Cascading Rules * Prepping Data * Re-populating the form * Callbacks: Your own Validation Methods * Setting Error Messages * Translating Field Names * Changing the Error Delimiters * Showing Errors Individually * Validating an Array (other than $_POST) – Saving Sets of Validation Rules to a Config File * How to save your rules * Creating Sets of Rules * Calling a Specific Rule Group * Associating a Controller Method with a Rule Group – Using Arrays as Field Names – Rule Reference – Prepping Reference – Class Reference * $this->form_validation->set_rules() * $this->form_validation->run() * $this->form_validation->set_message() * $this->form_validation->set_data() * $this->form_validation->reset_validation() * $this->form_validation->error_array() – Helper Reference * form_error() * validation_errors() * set_value() * set_select() * set_checkbox() * set_radio()

Overview

Before explaining CodeIgniter’s approach to data validation, let’s describe the ideal scenario: 1. A form is displayed. 2. You fill it in and submit it. 3. If you submitted something invalid, or perhaps missed a required item, the form is redisplayed containing your data along with an error message describing the problem.

7.1. Libraries 101 CodeIgniter Documentation, 3.0-dev

4. This process continues until you have submitted a valid form. On the receiving end, the script must: 1. Check for required data. 2. Verify that the data is of the correct type, and meets the correct criteria. For example, if a username is submitted it must be validated to contain only permitted characters. It must be of a minimum length, and not exceed a maximum length. The username can’t be someone else’s existing username, or perhaps even a reserved word. Etc. 3. Sanitize the data for security. 4. Pre-format the data if needed (Does the data need to be trimmed? HTML encoded? Etc.) 5. Prep the data for insertion in the database. Although there is nothing terribly complex about the above process, it usually requires a significant amount of code, and to display error messages, various control structures are usually placed within the form HTML. Form validation, while simple to create, is generally very messy and tedious to implement.

Form Validation Tutorial

What follows is a “hands on” tutorial for implementing CodeIgniters Form Validation. In order to implement form validation you’ll need three things: 1.A View file containing a form. 2. A View file containing a “success” message to be displayed upon successful submission. 3.A controller method to receive and process the submitted data. Let’s create those three things, using a member sign-up form as the example.

The Form

Using a text editor, create a form called myform.php. In it, place this code and save it to your application/views/ folder: My Form

Username

Password

Password Confirm

Email Address

102 Chapter 7. CodeIgniter Documentation, 3.0-dev

The Success Page

Using a text editor, create a form called formsuccess.php. In it, place this code and save it to your application/views/ folder: My Form

Your form was successfully submitted!

The Controller

Using a text editor, create a controller called form.php. In it, place this code and save it to your application/controllers/ folder:

public function index() { $this->load->helper(array(’form’, ’url’));

$this->load->library(’form_validation’);

if ($this->form_validation->run() == FALSE) { $this->load->view(’myform’); } else { $this->load->view(’formsuccess’); } } }

Try it!

To try your form, visit your site using a URL similar to this one:

7.1. Libraries 103 CodeIgniter Documentation, 3.0-dev

example.com/index.php/form/

If you submit the form you should simply see the form reload. That’s because you haven’t set up any validation rules yet. Since you haven’t told the Form Validation class to validate anything yet, it returns FALSE (boolean false) by default. ‘‘The run()‘‘ method only returns TRUE if it has successfully applied your rules without any of them failing.

Explanation

You’ll notice several things about the above pages: The form (myform.php) is a standard web form with a couple exceptions: 1. It uses a form helper to create the form opening. Technically, this isn’t necessary. You could create the form using standard HTML. However, the benefit of using the helper is that it generates the action URL for you, based on the URL in your config file. This makes your application more portable in the event your URLs change. 2. At the top of the form you’ll notice the following function call:

This function will return any error messages sent back by the validator. If there are no messages it returns an empty string. The controller (form.php) has one method: index(). This method initializes the validation class and loads the form helper and URL helper used by your view files. It also runs the validation routine. Based on whether the validation was successful it either presents the form or the success page.

Setting Validation Rules

CodeIgniter lets you set as many validation rules as you need for a given field, cascading them in order, and it even lets you prep and pre-process the field data at the same time. To set validation rules you will use the set_rules() method: $this->form_validation->set_rules();

The above method takes three parameters as input: 1. The field name - the exact name you’ve given the form field. 2. A “human” name for this field, which will be inserted into the error message. For example, if your field is named “user” you might give it a human name of “Username”. 3. The validation rules for this form field.

: If you would like the field name to be stored in a language file, please see Translating Field Names.

Here is an example. In your controller (form.php), add this code just below the validation initialization method: $this->form_validation->set_rules(’username’, ’Username’, ’required’); $this->form_validation->set_rules(’password’, ’Password’, ’required’); $this->form_validation->set_rules(’passconf’, ’Password Confirmation’, ’required’); $this->form_validation->set_rules(’email’, ’Email’, ’required’);

Your controller should now look like this:

104 Chapter 7. CodeIgniter Documentation, 3.0-dev

public function index() { $this->load->helper(array(’form’, ’url’));

$this->load->library(’form_validation’);

$this->form_validation->set_rules(’username’, ’Username’, ’required’); $this->form_validation->set_rules(’password’, ’Password’, ’required’); $this->form_validation->set_rules(’passconf’, ’Password Confirmation’, ’required’); $this->form_validation->set_rules(’email’, ’Email’, ’required’);

if ($this->form_validation->run() == FALSE) { $this->load->view(’myform’); } else { $this->load->view(’formsuccess’); } } }

Now submit the form with the fields blank and you should see the error messages. If you submit the form with all the fields populated you’ll see your success page.

: The form fields are not yet being re-populated with the data when there is an error. We’ll get to that shortly.

Setting Rules Using an Array

Before moving on it should be noted that the rule setting method can be passed an array if you prefer to set all your rules in one action. If you use this approach, you must name your array keys as indicated: $config = array( array( ’field’ => ’username’, ’label’ => ’Username’, ’rules’ => ’required’ ), array( ’field’ => ’password’, ’label’ => ’Password’, ’rules’ => ’required’ ), array( ’field’ => ’passconf’, ’label’ => ’Password Confirmation’, ’rules’ => ’required’ ), array( ’field’ => ’email’, ’label’ => ’Email’, ’rules’ => ’required’

7.1. Libraries 105 CodeIgniter Documentation, 3.0-dev

) );

$this->form_validation->set_rules($config);

Cascading Rules

CodeIgniter lets you pipe multiple rules together. Let’s try it. Change your rules in the third parameter of rule setting method, like this:

$this->form_validation->set_rules(’username’, ’Username’, ’required|min_length[5]|max_length[12]|is_unique[users.username]’); $this->form_validation->set_rules(’password’, ’Password’, ’required’); $this->form_validation->set_rules(’passconf’, ’Password Confirmation’, ’required|matches[password]’); $this->form_validation->set_rules(’email’, ’Email’, ’required|valid_email|is_unique[users.email]’);

The above code sets the following rules: 1. The username field be no shorter than 5 characters and no longer than 12. 2. The password field must match the password confirmation field. 3. The email field must contain a valid email address. Give it a try! Submit your form without the proper data and you’ll see new error messages that correspond to your new rules. There are numerous rules available which you can read about in the validation reference.

: You can also pass an array of rules to set_rules(), instead of a string. Example: $this->form_validation->set_rules(’username’, ’Username’, array(’required’, ’min_length[5]’));

Prepping Data

In addition to the validation method like the ones we used above, you can also prep your data in various ways. For example, you can set up rules like this:

$this->form_validation->set_rules(’username’, ’Username’, ’trim|required|min_length[5]|max_length[12]|xss_clean’); $this->form_validation->set_rules(’password’, ’Password’, ’trim|required|md5’); $this->form_validation->set_rules(’passconf’, ’Password Confirmation’, ’trim|required|matches[password]’); $this->form_validation->set_rules(’email’, ’Email’, ’trim|required|valid_email’);

In the above example, we are “trimming” the fields, converting the password to MD5, and running the username through the xss_clean() method, which removes malicious data. Any native PHP function that accepts one parameter can be used as a rule, like htmlspecialchars, trim, md5, etc.

: You will generally want to use the prepping functions after the validation rules so if there is an error, the original data will be shown in the form.

Re-populating the form

Thus far we have only been dealing with errors. It’s time to repopulate the form field with the submitted data. CodeIgniter offers several helper functions that permit you to do this. The one you will use most commonly is:

106 Chapter 7. CodeIgniter Documentation, 3.0-dev

set_value(’field name’)

Open your myform.php view file and update the value in each field using the set_value() function: Don’t forget to include each field name in the ‘‘set_value()‘‘ functions! My Form

Username

Password

Password Confirm

Email Address

Now reload your page and submit the form so that it triggers an error. Your form fields should now be re-populated

: The Class Reference section below contains functions that permit you to re-populate

For more info please see the Using Arrays as Field Names section below.

Callbacks: Your own Validation Methods

The validation system supports callbacks to your own validation methods. This permits you to extend the validation class to meet your needs. For example, if you need to run a database query to see if the user is choosing a unique username, you can create a callback method that does that. Let’s create an example of this. In your controller, change the “username” rule to this: $this->form_validation->set_rules(’username’, ’Username’, ’callback_username_check’);

7.1. Libraries 107 CodeIgniter Documentation, 3.0-dev

Then add a new method called username_check() to your controller. Here’s how your controller should now look:

public function index() { $this->load->helper(array(’form’, ’url’));

$this->load->library(’form_validation’);

$this->form_validation->set_rules(’username’, ’Username’, ’callback_username_check’); $this->form_validation->set_rules(’password’, ’Password’, ’required’); $this->form_validation->set_rules(’passconf’, ’Password Confirmation’, ’required’); $this->form_validation->set_rules(’email’, ’Email’, ’required|is_unique[users.email]’);

if ($this->form_validation->run() == FALSE) { $this->load->view(’myform’); } else { $this->load->view(’formsuccess’); } }

public function username_check($str) { if ($str == ’test’) { $this->form_validation->set_message(’username_check’, ’The {field} field can not be the word "test"’); return FALSE; } else { return TRUE; } }

}

Reload your form and submit it with the word “test” as the username. You can see that the form field data was passed to your callback method for you to process. To invoke a callback just put the method name in a rule, with “callback_” as the rule prefix. If you need to receive an extra parameter in your callback method, just add it normally after the method name between square brackets, as in: “callback_foo**[bar]**”, then it will be passed as the second argument of your callback method.

: You can also process the form data that is passed to your callback and return it. If your callback returns anything other than a boolean TRUE/FALSE it is assumed that the data is your newly processed form data.

Setting Error Messages

All of the native error messages are located in the following language file: sys- tem/language/english/form_validation_lang.php

108 Chapter 7. CodeIgniter Documentation, 3.0-dev

To set your own custom message you can either edit that file, or use the following method: $this->form_validation->set_message(’rule’, ’Error Message’);

Where rule corresponds to the name of a particular rule, and Error Message is the text you would like displayed. If you’d like to include a field’s “human” name, or the optional parameter some rules allow for (such as max_length), you can add the {field} and {param} tags to your message, respectively: $this->form_validation->set_message(’min_length’, ’{field} must have at least {param} characters.’);

On a field with the human name Username and a rule of min_length[5], an error would display: “Username must have at least 5 characters.”

: The old sprintf() method of using %s in your error messages will still work, however it will override the tags above. You should use one or the other.

In the callback rule example above, the error message was set by passing the name of the method (without the “call- back_” prefix): $this->form_validation->set_message(’username_check’)

Translating Field Names

If you would like to store the “human” name you passed to the set_rules() method in a language file, and therefore make the name able to be translated, here’s how: First, prefix your “human” name with lang:, as in this example: $this->form_validation->set_rules(’first_name’, ’lang:first_name’, ’required’);

Then, store the name in one of your language file arrays (without the prefix): $lang[’first_name’] = ’First Name’;

: If you store your array item in a language file that is not loaded automatically by CI, you’ll need to remember to load it in your controller using: $this->lang->load(’file_name’);

See the Language Class page for more info regarding language files.

Changing the Error Delimiters

By default, the Form Validation class adds a paragraph tag (

) around each error message shown. You can either change these delimiters globally, individually, or change the defaults in a config file. 1. Changing delimiters Globally To globally change the error delimiters, in your controller method, just after loading the Form Validation class, add this: $this->form_validation->set_error_delimiters(’

’, ’
’);

In this example, we’ve switched to using div tags. 2. Changing delimiters Individually Each of the two error generating functions shown in this tutorial can be supplied their own delimiters as follows:

7.1. Libraries 109 CodeIgniter Documentation, 3.0-dev

’, ’